IF-THEN/ELSE Statements

IF-THEN and IF-THEN/ELSE statements are conditional statements in SAS that we can use to control the execution of our code. These can be used in a DATA step or in open code in a %macro with a % preceding the key words as illustrated below.

In a DATA step

data out.if_then_example;
    set out.fake_micro(keep = pik mom_pik dad_pik);
    
        * Identify parent status;
        if mom_pik ~= "" and dad_pik ~= "" then singleparent = 0;
        else singleparent = 1;  
run; 
pik mom_pik dad_pik singleparent
0 141 173 NaN 1.0
1 138 149 NaN 1.0
2 177 NaN 003 1.0
3 146 013 004 0.0
4 104 187 005 0.0
5 144 NaN 006 1.0
6 083 025 007 0.0
7 115 NaN 008 1.0
8 170 157 009 0.0
9 118 NaN 010 1.0
10 085 NaN 011 1.0
11 051 058 NaN 1.0
12 197 156 013 0.0
13 054 034 NaN 1.0
14 139 NaN 015 1.0
15 111 004 NaN 1.0
16 008 NaN 017 1.0
17 055 NaN 018 1.0
18 167 072 NaN 1.0
19 160 NaN 020 1.0
20 163 112 NaN 1.0
21 030 NaN 022 1.0
22 097 NaN 023 1.0
23 026 NaN 024 1.0
24 039 NaN 025 1.0
25 179 NaN 026 1.0
26 154 NaN 027 1.0
27 047 NaN 028 1.0
28 009 NaN 029 1.0
29 103 NaN 030 1.0
30 188 NaN 031 1.0
31 028 NaN 032 1.0
32 041 NaN 033 1.0
33 001 NaN 034 1.0
34 162 NaN 035 1.0
35 064 136 036 0.0
36 175 NaN 037 1.0
37 183 NaN 038 1.0
38 093 NaN 039 1.0
39 136 NaN 040 1.0
40 140 191 041 0.0
41 003 001 NaN 1.0
42 176 NaN 043 1.0
43 108 090 044 0.0
44 194 NaN 045 1.0
45 187 055 046 0.0
46 015 161 047 0.0
47 062 NaN 048 1.0
48 130 NaN 049 1.0
49 029 NaN 050 1.0

And in open code

%macro ifthen(year);

    %if %sysfunc(mod(&year, 2)) = 0 %then %put Even.;
    %else %put Odd.;

%mend ifthen;

%ifthen(1);
%ifthen(2);
581  %ifthen(1);
Odd.
582  %ifthen(2);
Even.

IF-THEN/ELSE DO Statements

Sometimes we want to execute a series of statements depending on a certain condition rather than just one statement. In these instances, we use IF-THEN/ELSE DO statements. The syntax for these statements in a DATA step is:

data out.output;
    set in.input;
    
    * IF-THEN DO;
    if (cond) then do;
        /* SAS statements if condition is met */
    end;
    
    * IF-THEN/ELSE DO;
    if (cond) then do;
        /* SAS statements if condition is met */
    end;
    else do;
        /* SAS statements if condition is not met */
    end;
run;

Or in open code (wrapped in a %macro)

* IF-THEN DO;
%macro ifthendo;
    %if (cond) %then %do;
        /* SAS statements if condition is met */
    %end;

    * IF-THEN/ELSE DO;
    %if (cond) %then %do;
        /* SAS statements if condition is met */
    %end;
    %else %do;
        /* SAS statements if condition is not met */
    %end;
%mend ifthendo;