How to Use IF AND Logic in SAS


You can use the following basic syntax to use IF AND logic in SAS:

data new_data;
    set my_data;
    if team="Cavs" and points>20 then cavs_and_20 = 1;
    else cavs_and_20 = 0;
run;

This particular example creates a new dataset with a column called cavs_and_20 that takes on the following values:

  • 1 if the value in the team column is equal to “Cavs” and if the value in the points column is greater than 20.
  • 0 if both conditions aren’t met.

The following example shows how to use this syntax in practice.

Example: How to Use IF AND Logic in SAS

Suppose we have the following dataset in SAS that contains information about various basketball players:

/*create dataset*/
data my_data;
    input team $ points;
    datalines;
Cavs 12
Cavs 24
Warriors 15
Cavs 26
Warriors 14
Celtics 36
Celtics 19
;
run;

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

Suppose we would like to create a new dataset with a column that takes on the following values:

  • 1 if the value in the team column is equal to “Cavs” and if the value in the points column is greater than 20.
  • 0 if both conditions aren’t is met.

We can use the following syntax to do so:

/*create new dataset*/
data new_data;
    set my_data;
    if team="Cavs" and points>20 then cavs_and_20 = 1;
    else cavs_and_20 = 0;
run;

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

The new column called cavs_and_20 uses IF AND logic to determine if each row in the dataset should have a value of 0 or 1.

We can see that there are two rows where the team name is Cavs and the points value is greater than 20.

Both of these rows receive a value of 1 in the new cavs_and_20 column.

No other rows meet both conditions, so all other rows receive a value of 0 in the cavs_and_20 column.

Additional Resources

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

How to Rename Variables in SAS
How to Create New Variables in SAS
How to Replace Characters in a String in SAS

Leave a Reply

Your email address will not be published. Required fields are marked *