Conditional Logic in SAS – IF-ELSE and DO Statement

Welcome back to Mindful Data Minds! In this session, we’ll learn how to use IF-ELSE statements to apply conditions in SAS, and how the DO statement helps when multiple actions need to be performed under one condition.

Watch the Full Tutorial

What You Will Learn

  • How to use IF-ELSE for conditional logic.
  • How to avoid truncation issues with character variables.
  • How to output data into multiple datasets in one step.
  • How to use DO…END for multiple actions under one condition.
  • How to apply business rules (like discounts) using conditional logic.

Using IF-ELSE in SAS

The IF-ELSE statement lets you apply logic to create new variables or categorize data.

Example: Categorizing Car Speed by Horsepower

data a;
   sashelp.cars;
   if horsepower <= 250 then speed = "Slow";
   else if 250 < horsepower <= 400 then speed = "Medium";
   else speed = "Fast";
run;

Result: A new column Speed is created based on horsepower.

Note: By default, SAS sets the length of character variables based on the first value it encounters. If the first value is “Slow” (4 characters), longer values like “Medium” may get truncated

Solution: Define a format or length:

format speed $10.;

Creating Multiple Datasets with IF-ELSE

You can output data into different datasets in a single step:

data slow medium fast;
   set b;
   if strip(lowcase(speed)) = "slow" then output slow;
   else if strip(lowcase(speed)) = "medium" then output medium;
   else output fast;
run;

Result: Three datasets (slow, medium, fast) created based on speed categories.

Using DO Statement

When multiple actions are needed under one condition, use DO…END.

Example: Applying Discounts Based on Speed

data c;
   set b;
   if strip(lowcase(speed)) = "slow" then do;
      discount = 10;
      updated_msrp = msrp - (msrp * discount / 100);
   end;
   else if strip(lowcase(speed)) = "medium" then do;
      discount = 5;
      updated_msrp = msrp - (msrp * discount / 100);
   end;
   else do;
      discount = 0;
      updated_msrp = msrp;
   end;
run;

Result:

  • Slow cars → 10% discount
  • Medium cars → 5% discount
  • Fast cars → No discount

The dataset now includes Discount and Updated MSRP columns.

Next Step

Continue learning by exploring the next tutorial in this series. Also subscribe to get notified about new lessons.

Have a Question?

Drop your doubts in the comments below or contact us.

Leave a Reply

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