BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
_maldini_
Barite | Level 11

I am trying to use the SUBSTRING function to extract a single character from a 60 character string. I want to create 60 new variables (D1, D2, etc.) each containing a sequential digit in the string. In other words, D1 contains the first digit of the string. D2 contains the second digit of the string. D3 contains the 3rd digit of the string, etc. There are multiple observations in the dataset.

 

My code is inadequate, but pasted below for reference. Thanks for any ideas you may have.

 

data want (drop=i);
set have;

array D(60);
array seq(60);

do i = 1 to 60;
D[i] = substr(seq[i], 1, 1);
* How do I write this so it will jump from the first position to the next position in the sequence automatically?
end;
run;

 

1 ACCEPTED SOLUTION

Accepted Solutions
Reeza
Super User

Use the CHAR() function instead. 

 

CHAR(string, position)

String -> always the same

position -> loop counter, in this case i

 

SUBSTR(STRING, start, length)

 

String -> Should always be the same

Start -> loop counter, in this case i

length -> always 1.

 

D[i] = substr(STRING_VARIABLE, i, 1);

View solution in original post

3 REPLIES 3
Reeza
Super User

Use the CHAR() function instead. 

 

CHAR(string, position)

String -> always the same

position -> loop counter, in this case i

 

SUBSTR(STRING, start, length)

 

String -> Should always be the same

Start -> loop counter, in this case i

length -> always 1.

 

D[i] = substr(STRING_VARIABLE, i, 1);
Astounding
PROC Star

One more item you might want to attend to ... assign a length to the new variables:

 

array D {60} $ 1;

 

Otherwise, the length of the new variables will default to the same length as the original incoming character string.

RW9
Diamond | Level 26 RW9
Diamond | Level 26

Could I ask why.  It is rarely beneficial to create many variables such as you are doing, in terms of programming.  For all your subsequent programming you then need to know how many there are, which could vary.  Are you doing some sort of agregates or maths on them, as you can probably do that straight from the string (or if necessary output one row per character).  Would make you life much easier.

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 4364 views
  • 3 likes
  • 4 in conversation