Home » How to Use IF-THEN-ELSE in SAS (With Examples)

How to Use IF-THEN-ELSE in SAS (With Examples)

by Erma Khan

You can use an IF-THEN-ELSE statement in SAS to return some value if some condition is true, else return another value if some condition is not true.

This statement uses the following basic syntax:

if var1 > 30 then var2 = 'good';
else var2 = 'bad';

You can also chain together several ELSE IF statements to return more potential values based on more conditions:

if var1 > 35 then var2 = 'great';
else if var1 > 30 then var2 = 'good';
else var2 = 'bad';

The following examples show how to use each of these statements in practice with the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $ points;
    datalines;
Cavs 12
Cavs 14
Warriors 15
Hawks 18
Mavs 31
Mavs 32 
Mavs 35
Celtics 36
Celtics 40
;
run;

/*view dataset*/
proc print data=original_data;

Example 1: IF-THEN-ELSE in SAS

We can use the following IF-THEN-ELSE statement to create a new variable called rating that takes on a value of “good” if the value in the points column is greater than 30 or a value of “bad” otherwise:

/*create new dataset with new variable called rating*/
data new_data;
    set original_data;
    if points > 30 then rating = 'good';
    else rating = 'bad';
run;

/*view new dataset*/
proc print data=new_data;

Notice that the new column called rating takes on a value of “good” if the value in the points column is greater than 30 or a value of “bad” otherwise.

Example 2: IF-THEN-ELSE IF in SAS

We can use the following IF-THEN-ELSE IF statement to create a new variable called rating that takes on the following values:

  • “great” if points is greater than 35
  • else, “good” if points is greater than 30
  • else, “bad”

The following code shows how to do so:

/*create new dataset with new variable called rating*/
data new_data;
    set original_data;
    if points > 35 then rating = 'great';
    else if points > 30 then rating = 'good';
    else rating = 'bad';
run;

/*view new dataset*/
proc print data=new_data;

The new column called rating takes on a value of “great”, “good”, or “bad” based on the corresponding value in the points column.

Note: Feel free to use as many ELSE IF statements as you’d like to return as many different values as you’d like based on various conditions.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Use IF-THEN-DO in SAS
How to Remove Duplicates in SAS
How to Replace Missing Values with Zero in SAS

Related Posts