This tutorial explains the difference between IF condition with %IF and DO END with %DO %END in SAS macros, with examples, to make it easier to understand.
1. IF statement cannot be used outside data step whereas %IF can be used outside and inside data step but within the macro.
In the following program, we are telling SAS to check the value if it is greater than 10 then run PROC MEANS procedure.
Please note that %IF works to run procedures.
%macro temp(N=); %if &N. > 10 %then %do; proc means data = sashelp.class MEAN; var age; run; %end; %else %put better luck next time; %mend; %temp(N=19);
IF Statement does not work to run procedure.
%macro temp2(N=); data _null_; if &N. > 10 then do; proc means data = sashelp.class MEAN; var age; run; end; else put "the value is less than or equal to 10"; run; %mend; %temp2(N=11);
2. The %IF can only be used inside of a macro. In other words, you cannot use it in a program without it in a macro definition (%macro yourmacro; %mend;)
The following program does not work as the %IF is not valid outside macro.
%let N = 12; %if &N. > 10 %then %do; proc means data = sashelp.class MEAN; var age; run; %end; %else %put better luck next time;
3. SAS Macro will be executed first and once completed, data step statements will be executed.
%macro test; data temp; do j =1 to 5; N = j *5; put N; %let i = 1; %if &i %then %put the value of i is equal to 1; end; run; %mend; %test;
Initially SAS checks for macro statements/macro variables and executing them. In this case, it sets i is equal to 1, then writes a log " the value of i is equal to 1". Once this process is completed, it checks DO LOOP and run iterations and multiply each iteration value by 5 and prints to the log.
If you are generating code to automate repetitive task within a data step, and you can use either %do-%end or do-end.
In the following program, we are generating 5 values starting from 5 and ends with 25 with the difference of 5 between values.
data temp; do j =1 to 5; N = j *5; output; end; drop j; run;
%macro test; data temp; %do j = 1 %to 5; N = &j. *5; output; %end; run; %mend; %test;
Thank you very much sir, this is very clear and well formatted to read!
ReplyDelete