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


You can use an IF-THEN-DO statement in SAS to do a block of statements if some condition is true.

This statement uses the following basic syntax:

if var1 = "value" then do;
    new_var2 = 10;
    new_var3 = 5;
    end;

Note: An IF-THEN statement is used when you only want to do one statement. An IF-THEN-DO statement is used when you want to do several statements.

The following example shows how to use an IF-THEN-DO statement in practice.

Example: IF-THEN-DO in SAS

Suppose we have the following dataset in SAS that shows the total sales made by two stores during consecutive days:

/*create dataset*/
data original_data;
    input store $ sales;
    datalines;
A 14
A 19
A 22
A 20
A 16
A 26
B 40
B 43
B 29
B 30
B 35
B 33
;
run;

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

We can use the following IF-THEN-DO statement to create two new variables that take on certain values if the store is equal to “A” in the original dataset:

/*create new dataset*/
data new_data;
    set original_data;
    if store = "A" then do;
    region="East";
    country="Canada";
    end;
run;

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

IF-THEN-DO statement in SAS

Here’s how this chunk of code worked:

If the store was equal to “A” then a new variable called region was created with a value of “East” and a new variable called country was created with a value of “Canada.”

Note that we can use multiple IF-THEN-DO statements as well:

/*create new dataset*/
data new_data;
    set original_data;

    if store = "A" then do;
    region="East";
    country="Canada";
    end;

    if store = "B" then do;
    region="West";
    country="USA";
    end; 
run;

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

Here’s how this chunk of code worked:

  • If the store was equal to “A” then a new variable called region was created with a value of “East” and a new variable called country was created with a value of “Canada.”
  • If the store was equal to “B” then the value for region was “West” and the value for country was “USA.”

Additional Resources

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

How to Normalize Data in SAS
How to Remove Duplicates in SAS
How to Replace Missing Values with Zero in SAS

Leave a Reply

Your email address will not be published.