Dick Duck's SAS tips

This is the nest where I keep my SAS eggs. It's all here... Arrays, control loops, links to online SAS resources, you name it.

Monday, February 20, 2006

Comparing if, else if and select

Suppose we have a paper with sixteen item. We want to set the maximum number of marks for each of the items. We could just code:

if item = 1 then maxmark = 4;
if item = 2 then maxmark = 6;
if item = 3 then maxmark = 6;
if item = 4 then maxmark = 9;
if item = 5 then maxmark = 4;
if item = 6 then maxmark = 6;
if item = 7 then maxmark = 6;
if item = 8 then maxmark = 9;
if item = 9 then maxmark = 4;
if item = 10 then maxmark = 6;
if item = 11 then maxmark = 6;
if item = 12 then maxmark = 9;
if item = 13 then maxmark = 4;
if item = 14 then maxmark = 6;
if item = 15 then maxmark = 6;
if item = 16 then maxmark = 9;
Suppose we have 2000 candidates, or 32,000 items. The above code would have to interpret 32,000 if-statements. How about this:

if item in (1, 5, 9, 13) then maxmark = 4;
else if item in (2, 3, 6, 7, 10, 11, 14, 15) then maxmark = 6;
else maxmark = 9;
Apart from being more succinct, by using 'in' and 'else', the code now only needs to interpret 2500 if-statements. We can do even better, by putting the most frequent case first:

if item in (2, 3, 6, 7, 10, 11, 14, 15) then maxmark = 6;
else if item in (1, 5, 9, 13) then maxmark = 4;
else maxmark = 9;
The code is a bit less accessible, but now only 2000 if-statements need to be evaluated. But there is a third way:

select (item);
when (1, 5, 9, 13) maxmark = 4;
when (2, 3, 6, 7, 10, 11, 14, 15) maxmark = 6;
when (4, 8, 12, 16) maxmark = 9; /* or: otherwise maxmark = 9 */
end;
This has the same computational load as the previous code using 'if else if', but it is clearer what is going on. Furthermore, you can be assured that this code is always the most computationally efficient.

0 Comments:

Post a Comment

<< Home