Search code examples
sassas-macro

Syntax issue when using macro in SAS


I would like to write a macro. Its function is to receive dataset, divide the dataset into several groups, count the sample size of each group, and finally create a variable call "ind" to indicate whether this group size is large or not. (ind=0 means small, ind=1 means large).

I first wrote code outside of macro, which run well. I got the ideal output without error.

data stu; input group score; datalines; 
1 700
1 850
1 820
1 640
1 920
1 480
1 460
1 500
2 570
2 580
run;

proc freq data=stu;
table group/out=count;
run;

data count; set count;
if count>=3 then ind=1; else ind=0;
run;

proc print data=count;run;

However, when I tried to use macro to realize this function:

%macro tests(data=, group=);

proc freq data=&data;
table &group/out=freqn;
run;

data count; set freqn;
%if count>=3 %then ind=1; %else ind=0;
run;

proc print data=count;run;

%mend tests;

%tests(data=stu, group=group);

Dataset "count" cannot be generated and I also got an error:

ERROR 22-322: Syntax error, expecting one of the following: !, !!, &, *,
 **, +, -, /, <, <=, <>, =, >, ><, >=, AND, EQ, GE, GT, LE,
 LT, MAX, MIN, NE, NG, NL, OR, ^=, |, ||, ~=.

How could this happen?

Thanks.


Solution

  • I figured it out: Within a datastep, the if-then statements should not have a % in front. So the macro code should be:

    %macro tests(data=, group=);
    
    proc freq data=&data;
    table &group/out=freqn;
    run;
    
    data count; set freqn;
    if count>=3 then ind=1; else ind=0;
    run;
    
    proc print data=count;run;
    
    %mend tests;
    
    %tests(data=stu, group=group)
    

    (hope it could help SAS starters who may also make stupid mistakes like me)