I am trying to make three separate variables based on the value in one variable. I may have multiple rows per ID and each row can be a code 1-3 in one variable (HAVE). I want to create a new variable for each value of HAVE (Want1 - Want3) and if a value appears in any of the rows for that ID then I want to place the value in the new variable even if that row has a different value for HAVE.
do i need to loop through dataset to create each variable variable separately?
ID | Have | Want1 | Want2 | Want3 |
A | 3 | 2 | 3 | |
A | 3 | 2 | 3 | |
A | 3 | 2 | 3 | |
A | 2 | 2 | 3 | |
B | 1 | 1 | 2 | |
B | 1 | 1 | 2 | |
B | 2 | 1 | 2 |
Here's an approach that has a strict requirement. The new variables (WANT1, WANT2, and WANT3) must not exist in the original data. Then assuming your data set is sorted by ID, you could use:
data want;
do until (last.id);
set have;
by id;
if have=1 then want1=1;
else if have=2 then want2=2;
else if have=3 then want3=3;
end;
do until (last.id);
set have;
by id;
output;
end;
run;
The trick is that the top and bottom DO loops read exactly the same set of observations. The top loop sets values for the new variables. The bottom loop outputs the observations with the values set by the top loop.
Here's an approach that has a strict requirement. The new variables (WANT1, WANT2, and WANT3) must not exist in the original data. Then assuming your data set is sorted by ID, you could use:
data want;
do until (last.id);
set have;
by id;
if have=1 then want1=1;
else if have=2 then want2=2;
else if have=3 then want3=3;
end;
do until (last.id);
set have;
by id;
output;
end;
run;
The trick is that the top and bottom DO loops read exactly the same set of observations. The top loop sets values for the new variables. The bottom loop outputs the observations with the values set by the top loop.
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
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.