Chuyển đến nội dung

Bài 8 · Environment and Data Steps

Conditional Logic in SAS: IF-THEN/ELSE, DO and SELECT

Make decisions in a DATA step: IF-THEN/ELSE chains, DO groups, SELECT-WHEN, comparison and logical operators, the IN operator and how missing values and string lengths behave.

Real data needs decisions: assign a grade band, flag unusual values, treat different groups differently. SAS offers two main tools: the IF-THEN/ELSE statement and the SELECT group. This lesson also covers the operators and two traps that catch nearly everyone: missing values and character lengths.

IF-THEN and ELSE

SAS
data graded;
   set sashelp.class;
   if age < 12 then group = "child";
   else if age < 15 then group = "teen";
   else group = "older";
run;

SAS tests the conditions in order and executes the first branch that is true; the rest are skipped. Put the most likely or most restrictive condition first, and always finish with a plain else as a catch-all, so every observation gets a value.

Without else, each if is tested independently. That wastes time and can set a value twice when conditions overlap.

Executing several statements: DO and END

A THEN clause runs exactly one statement. To run several, wrap them in a DO group:

SAS
data flagged;
   set sashelp.class;
   if weight > 100 then do;
      heavy = 1;
      note = "check weight";
   end;
   else do;
      heavy = 0;
      note = " ";
   end;
run;

Every do; must have a matching end;. Indent the body so the structure is visible.

Comparison and logical operators

Meaning Symbol Mnemonic
Equal = EQ
Not equal ^= or ~= NE
Less than / greater than < > LT GT
At most / at least <= >= LE GE
And, or, not & | ^ AND OR NOT
In a list IN
SAS
if sex = "F" and age >= 14 then group = "older girls";
if age in (11, 12, 13) then band = "early";
if not (height > 60 or weight > 100) then small = 1;

AND is evaluated before OR, so use parentheses whenever you mix them. Character comparisons are case-sensitive: "f" is not "F". Normalize first with upcase(sex) = "F".

SAS has a shortcut for ranges: 18 <= age <= 65 works as you would expect in mathematics, unlike most languages.

Truth in SAS

SAS has no boolean type. An expression is true if it is any number other than 0 or missing, and false if it is 0 or missing. Comparisons return 1 for true and 0 for false, so you can store them directly: is_teen = (age >= 13);.

Missing values in comparisons

A missing numeric value (.) is smaller than every real number, including negatives. That means:

SAS
if income < 30000 then low = 1;   /* TRUE when income is missing! */

Guard explicitly: if not missing(income) and income < 30000 then low = 1;. The missing() function works for both numeric and character variables. This trap silently inflates counts, so test for missing first.

SELECT-WHEN

When one expression is compared with many values, SELECT is cleaner than a long else if chain:

SAS
data regions;
   set sashelp.class;
   select (age);
      when (11, 12)  stage = "young";
      when (13, 14)  stage = "middle";
      when (15, 16)  stage = "older";
      otherwise      stage = "unknown";
   end;
run;

If a when has several statements, use do; ... end;. Add an otherwise, since SAS reports an error at run time if no when matches and there is no otherwise. You can also write select; with no expression and put full conditions in the when clauses:

SAS
select;
   when (bmi < 18.5) cat = "under";
   when (bmi < 25)   cat = "normal";
   otherwise         cat = "over";
end;

Trap: character length

SAS fixes a character variable's length the first time it sees it. In this step:

SAS
data oops;
   set sashelp.class;
   if age < 14 then size = "small";
   else size = "medium-sized";
run;

the first assignment sets size to length 5, so "medium-sized" is cut to "mediu". The log may not complain at all. Declare the length first:

SAS
length size $ 12;

Subsetting IF

An IF statement with no THEN is a subsetting if: the observation continues only if the condition is true, otherwise it is discarded:

SAS
data adults;
   set sashelp.class;
   if age >= 15;
run;

You will compare this with WHERE in Subsetting and Selecting Data.

Try the logic

This Python stand-in (not SAS) reproduces the branch order, a missing value that sorts low, and the length truncation of a character variable.

Python Python stand-in: IF-THEN/ELSE, missing values and length

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. In SAS, which values count as FALSE?

    Any number other than 0 or missing is true; 0 and missing are false.
  2. 2. How does a missing numeric value compare with 30000?

    Missing is smaller than every real number, so 'income < 30000' is true for missing income.
  3. 3. What goes wrong in: if age < 14 then size = 'small'; else size = 'medium-sized';

    The first value sets the length. Use a LENGTH statement before the if.
  4. 4. Which statement is a subsetting IF?

    An IF with no THEN keeps only observations for which the condition is true.

Summary

  • Chain tests with if / else if / else; use do; ... end; for several statements.
  • Use mnemonics or symbols for operators and parentheses to mix and and or.
  • True means non-zero and non-missing; missing is smaller than any number, so test missing() first.
  • select (x); when (...) ...; otherwise ...; end; replaces long else-if chains.
  • Declare length of new character variables before assigning.

Next: Functions and Dates

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.