BookmarkSubscribeRSS Feed
Ltwo
Fluorite | Level 6

 

Hi, I'm looking to create a substr of a variable that is of an uncertain length. The character variable I'm looking at in particular always starts with a number followed by a category, BUT the number and categories vary in length etc.

 

Sample data below.

 

data sample;
input var1 $;
datalines;
1a
11b
12b(i)
12b(ii)
12c(iii)
;
run;

And what I want to end up with is as below

 

data want;
input var1 $ number $ category $;
datalines;
1a 1 a
11b 11 b
12b(i) 12 b(i)
12b(ii) 12 b(ii)
12c(iii) 12 c(iii)
;
run;

How can I go about doing a substr here? Or is there a different SAS function I can use?

2 REPLIES 2
bstarr
Quartz | Level 8

In this case you might have better luck with the COMPRESS function. If you're not familiar with it, I strongly urge you to read the SAS documentation on it - it's quite a powerful function, which can allow you to keep or drop certain characters or types of characters (e.g. alphabetic characters, numbers). This step below will create what you need for this sample.

 

 

data want;
set sample;
    number = compress(var1,,'dk');
    category=compress(var1,,'d');
run;

 

 

Tom
Super User Tom
Super User

You might try using the perl regular expression functions, if you already know them.

But it is pretty easy to do with SUBSTR() and VERIFY() functions.

data want ;
  set sample;
  length number suffix $20;
  number=substrn(var1,1,verify(trim(var1),'1234567890')-1);
  suffix=substrn(var1,lengthn(number)+1);
run;

image.png 

SAS INNOVATE 2024

Innovate_SAS_Blue.png

Registration is open! SAS is returning to Vegas for an AI and analytics experience like no other! Whether you're an executive, manager, end user or SAS partner, SAS Innovate is designed for everyone on your team. Register for just $495 by 12/31/2023.

If you are interested in speaking, there is still time to submit a session idea. More details are posted on the website. 

Register now!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

Get the $99 certification deal.jpg

 

 

Back in the Classroom!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 2600 views
  • 0 likes
  • 3 in conversation