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;
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);
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);
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.
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 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.