Master SAS in 30 days!

A jargon-free, easy-to-learn SAS base course that is tailor-made for students with no prior knowledge of SAS.

If-Then-Else Statement in SAS

The IF-THEN-ELSE statement is used to conditionally process statement(s) when certain condition(s) are met.

Let's look at some examples.

The data set above contains 10 students and their exam results.
 

IF-THEN Statement

The IF-THEN statement tells SAS to execute a statement if the condition specified is true.

data students2;
set students;
if results > 50 then exam = "Pass";
run;

The if-then statement above executes the following statement when the result is greater than 50:
  • Exam = "Pass";

The ELSE statement is optional. It can be used to execute a statement if the condition is not true.

Example

data students2;
set students;
if results > 50 then exam = "Pass";
else exam = "Fail";
run;

The ELSE statement above tells SAS to assign the value "Fail" to the EXAM variable if the result is NOT greater than 50.

DO Group

In the example above, the following statement is executed when the result is greater than 50:

  • Exam = "Pass";


Sometimes, we might need to execute more than one statement when the condition is met. You can use the DO group to execute more than one statement in the IF-THEN statement.

Example

data students2;
set students;
if results <= 50 then do;
exam = "Fail";
Retake = "Yes";

end;
run;

The DO group starts with the DO statement. It tells SAS to execute the following two statements when the result is less than or equal to 50:
  • Exam = "Fail";
  • Retake = "Yes";

The DO group ends with the END statement.

When the result is not greater than 50, the character values "Fail" and "Yes" are assigned to the EXAM and RETAKE variables, respectively.
 

Do you have a hard time learning SAS?

Take our Practical SAS Training Course for Absolute Beginners and learn how to write your first SAS program!

IF Statement

The IF statement can also be used to subset a data set. 

Example

data students2;
set students;
if results > 70;
run;

In this example, the IF statement is used without the THEN statement.

This tells SAS to subset the data set and keep only the students whose result is greater than 70.
 

Master SAS in 30 Days

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
iconmail

Get latest articles from SASCrunch

SAS Base Certification Exam Prep Course

Two Certificate Prep Courses and 300+ Practice Exercises