We can use the CASE statement in SAS to create a new variable that uses case-when logic to determine the values to assign to the new variable.
This statement uses the following basic syntax:
proc sql;
select var1, case
when var2 = 'A' then 'North'
when var2 = 'B' then 'South'
when var2 = 'C' then 'East'
else 'West'
end as variable_name
from my_data;
quit;
The following example shows how to use the CASE statement in practice.
Example: Using the CASE Statement in SAS
Suppose we have the following dataset in SAS:
/*create dataset*/
data original_data;
input team $ points rebounds;
datalines;
A 25 8
A 18 12
A 22 6
B 24 11
B 27 14
C 33 19
C 31 20
D 30 17
D 18 22
;
run;
/*view dataset*/
proc print data=original_data;
We can use the following CASE statement to create a new variable called Division whose values are based on the values of the team variable:
/*create dataset*/
proc sql;
select team, points, case
when team = 'A' then 'North'
when team = 'B' then 'South'
when team = 'C' then 'East'
else 'West'
end as Division
from original_data;
quit;
Note that a new variable Division was created whose values are based on the values for the team variable.
Additional Resources
The following tutorials explain how to perform other common tasks in SAS:
How to Use IF-THEN-DO in SAS
How to Delete Rows in SAS
How to Remove Duplicates in SAS