How to use a SWITCH Statement in SAS

In SAS, the switch statement is called a SELECT statement.

SELECT <variable | expression>
  WHEN(condition) …
  <WHEN(condition) …>
  <WHEN(condition) …>

When a select expression is given, it evaluates this and does a relative jump, which is similar to the optimization done by a C or Java compiler in a switch statement. It doesn’t have any fall-throughs though, so it’s more like Ruby. It looks like this:

  when(0) put 'none';
  when(1) put 'one';
  when(2) put 'a couple';
  when(3,4,5) put 'a bunch';
  otherwise put 'a lot';

In SAS there’s a second mode for using it, where the expression after SELECT is left out. The closest similarity to another language I know of is PHP’s switch with switch(true) and using cases with conditions, however PHP’s version still has fall-through. Doing this in SAS looks like this:

  when(i<5) put 'lt 5';
  when(i=5) put 'eq 5';
  when(i>5) put 'gt 5';
  otherwise put 'math is broken';

The statement is basically syntactic sugar to make your code easier to read, and is logically no different from a chain of if/else-if/else-if/else statements. The statement will break out after the first statement evaluates true, even if statements further down would also evaluate true. It isn’t any different from

if(i<5) then put 'lt 5';
else if(i=5) then put 'eq 5';
else if(i>5) then put 'gt 5';
else put 'math is broken';

Possible advantages:

  • Statements can be reordered and/or dynamically inserted through SAS’s macro preprocessor runs without having to worry about if it needs an “if” or an “else if”.
  • For OCD-types, the formatting can look prettier.
  • For golfers, it uses fewer keystrokes.

One Comment

  • Posted September 5, 2012 at 9:40 am | Permalink

    I Love Your Website. Basically every post makes me lol, ponder,
    and learn something.

Post a Comment

Your email is kept private. Required fields are marked *