IF-THEN/ELSE Statement

Executes a SAS statement for observations that meet specific conditions.
Valid in: DATA step
Category: Control
Type: Executable

Syntax

IF expression THEN statement;
<ELSE statement;>

Arguments

expression
is any SAS expression and is a required argument.
statement
can be any executable SAS statement or DO group.

Details

SAS evaluates the expression in an IF-THEN statement to produce a result that is either nonzero, zero, or missing. A nonzero and nonmissing result causes the expression to be true; a result of zero or missing causes the expression to be false.
If the conditions that are specified in the IF clause are met, the IF-THEN statement executes a SAS statement for observations that are read from a SAS data set, for records in an external file, or for computed values. An optional ELSE statement gives an alternative action if the THEN clause is not executed. The ELSE statement, if used, must immediately follow the IF-THEN statement.
Using IF-THEN statements without the ELSE statement causes SAS to evaluate all IF-THEN statements. Using IF-THEN statements with the ELSE statement causes SAS to execute IF-THEN statements until it encounters the first true statement. Subsequent IF-THEN statements are not evaluated.
Note: For greater efficiency, construct your IF-THEN/ELSE statement with conditions of decreasing probability.

Comparisons

  • Use a SELECT group rather than a series of IF-THEN statements when you have a long series of mutually exclusive conditions.
  • Use subsetting IF statements, without a THEN clause, to continue processing only those observations or records that meet the condition that is specified in the IF clause.

Example: Different Ways of Specifying the IF-THEN/ELSE Statements

These examples show different ways of specifying the IF-THEN/ELSE statement.
  • if x then delete;
  • if status='OK' and type=3 then count+1;
  • if age ne agecheck then delete;
  • if x=0 then  
       if y ne 0 then put 'X ZERO, Y NONZERO'; 
       else put 'X ZERO, Y ZERO';
    else put 'X NONZERO';
  • if answer=9 then
       do;
          answer=.;
          put 'INVALID ANSWER FOR ' id=;
       end;
    else
       do;
          answer=answer10;
          valid+1;
       end;
  • data region;
       input city $ 1-30;
       if city='New York City'
          or city='Miami' then
          region='ATLANTIC COAST';
       else if city='San Francisco'
          or city='Los Angeles' then
             region='PACIFIC COAST';
       datalines;
    ...more data lines...
    ;