philihpAboutPGPLightning

How to use a SWITCH Statement in SAS

Philihp Busby,2 min read

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

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:

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

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:

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

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:

GitHub · Bluesky · LinkedIn · Instagram · KeybaseRSS

Built from 8f0906ac CC BY 4.0 — with love from San Francisco.