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.
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.