How to Use IF AND Logic in SAS

IF AND logic in SAS is used to execute a statement if two or more conditions are true at the same time. It is used to perform multiple comparisons and operations simultaneously and is written in the form of IF AND THEN . This statement is used to process a set of data and create a new one based on the two conditions given.


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.

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

x