I have a variable that contains a string of 9 numbers as values (e.g. 0000000100, 1110000100, etc.). These 9 numbers represent individual values (1 or 0). They were generated by a survey using radio buttons. If there is a 1 in the first position, it indicates a "Yes" to question number 1. If there is a 0 in the second position, it indicates a "No" to question number 2.
I need to create 9 new variables from each of the values in the string.
Var1 will get a 1 if the value in position one is 1. It will get a 0 if the value in position one is 0.
Var2 will get a 1 if the value in position 2 is 1. Etc.
How can I select specific values in a string like this?
I apologize if my description is unclear. I am a relative novice.
data want;
set have;
array answers (*) $ 1 A1-A9;
do i = 1 to 9;
answers(i) = substr(answer_string, i, 1);
end;
run;
data want;
answer_string = '101010101';
array answers (*) $ 1 A1-A9;
do i = 1 to 9;
answers(i) = substr(answer_string, i, 1);
end;
run;
Thanks @SASKiwi. Can I ask you a few clarifying questions?
<I assigned it just one value so you could understand the solution more easily.>
Got it. I guess I'm still not clear what to put here if the values are different from observation to observation.
Yes, I do have the data set and was planning on reading it in w/ a SET statement.
data want;
set have;
array answers (*) $ 1 A1-A9;
do i = 1 to 9;
answers(i) = substr(answer_string, i, 1);
end;
run;
I am using this array again for a similar purpose, and need some additional help.
<The SUBSTR function call has too many arguments.>
This time, the string is a maximum of 6 characters. Each value is 2 characters. In other words, a value of 010101 has 3 distinct values (01, 01, 01).
Ultimately, I want to create 3 new variables for each string:
IF VAR1=01 THEN NEW_VAR1=1; ELSE NEW_VAR1=0;
IF VAR2=01 THEN NEW_VAR2=1; ELSE NEW_VAR2=0;
Etc.
This code works for one variable:
DATA want; SET have; ARRAY answers (*) $ 2 VAR1-VAR3; DO i = 1 to 3; answers(i) = substr(_400203, i, 2); END; DROP _400203 i; RUN;
But this code does not work for multiple variables (In this example there are only 2 variables (_400203 and_400204), but I want to use it w/ 44 variables.
<The SUBSTR function call has too many arguments.>
DATA want; SET have ARRAY array_name (*) $ 2 VAR1-VAR6; DO i = 1 to 6; answers(i) = substr(_400203-_400204, i, 2); END; DROP _400203 _400204 i; RUN;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.