Skip to content
AgileLogics
6 min read

Conditional Logic

Prerequisites: Assignment statements and operators

IF-THEN/ELSE

data grades;
   input name $ score;
   length grade $ 2;
   if score >= 90 then grade = 'A';
   else if score >= 80 then grade = 'B+';
   else grade = 'C';
   datalines;
Ada 95
Alan 84
Grace 70
;
run;

proc print data=grades;
run;
Obs    name     score    grade

  1    Ada         95     A
  2    Alan        84     B+
  3    Grace       70     C

Only the first true branch runs. Each ELSE belongs to the IF just before it.

The length trap

Remove the LENGTH statement and Alan's grade becomes B. Without it, SAS sets grade's length from the first value it sees in the code — 'A', one character — so 'B+' is cut to 'B'. Always declare the length of character variables you create with IF-THEN.

Several statements: DO ... END

data bonus;
   input name $ sales;
   if sales > 10000 then do;
      bonus = sales * 0.05;
      tier = 'Gold';
   end;
   else do;
      bonus = 0;
      tier = 'Std';
   end;
   datalines;
Ada 12000
Alan 8000
;
run;

proc print data=bonus;
run;
Obs    name    sales    bonus    tier

  1    Ada     12000      600    Gold
  2    Alan     8000        0    Std

Here 'Gold' comes first, so tier has length 4 — enough for 'Std'.

SELECT

SELECT is cleaner than a long IF-ELSE chain when you compare one value against several options:

data regions;
   input city $ region $;
   length zone $ 8;
   select (region);
      when ('N', 'S') zone = 'Central';
      when ('E') zone = 'Coastal';
      otherwise zone = 'Other';
   end;
   datalines;
Leeds N
Dover E
Truro W
;
run;

proc print data=regions;
run;
Obs    city     region    zone

  1    Leeds      N       Central
  2    Dover      E       Coastal
  3    Truro      W       Other

Comparing text

Character comparisons are case-sensitive and ignore trailing blanks: 'abc' = 'abc ' is true, but 'abc' = 'ABC' is false. Compare with upcase(x) = 'ABC' when case shouldn't matter.

Practice

Classify each student in SASHELP.CLASS as short (height under 60), medium (60 to under 66), or tall, and print the first five.

Show solution
data sizes;
   set sashelp.class(obs=5);
   length size $ 6;
   if height < 60 then size = 'short';
   else if height < 66 then size = 'medium';
   else size = 'tall';
   keep name height size;
run;

proc print data=sizes;
run;
Obs    Name       Height    size

  1    Alfred      69.0     tall
  2    Alice       56.5     short
  3    Barbara     65.3     medium
  4    Carol       62.8     medium
  5    Henry       63.5     medium