Hi,
I have a table which variable names are created by macros as per example.
%LET VAR1 = JAN07; %LET VAR2 = JAN06; DATA HAVE; INPUT NAME $ &var1 &var2; DATALINES; aaaaa 100 50 bbbbb 110 60 ccccc 20 15 ddddd 300 290 eeeee 80 79 fffff 115 130 ; RUN;
How can I conditionally output from this? I have tried like this but seems like I'm missing something:
%MACRO MAC(); data WANT; SET HAVE; %IF &var2 LT 100 AND %SYSFUNC(abs(%EVAL(&VAR2 - &VAR1))) GE 5 %then %DO; output ; %END; %else %if &var2 GE 100 AND (%SYSFUNC(abs(%EVAL(&VAR2 - &VAR1))))/&VAR2 GE 0.05 %then %DO; output; %END; run; %MEND MAC; %MAC()
ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric operand is required. The condition was:
JAN06 - JAN07
ERROR: The function ABS referenced by the %SYSFUNC or %QSYSFUNC macro function has too few arguments.
ERROR: The macro MAC will stop executing.
There is no need for macro code when you want to do conditional logic on data.
Macro code is for code generation.
See if this works for you
%LET VAR1 = JAN07;
%LET VAR2 = JAN06;
DATA HAVE;
INPUT NAME $ &var1 &var2;
DATALINES;
aaaaa 100 50
bbbbb 110 60
ccccc 20 15
ddddd 300 290
eeeee 80 79
fffff 115 130
;
RUN;
data want;
set have;
if &var1 lt 100 and abs(&VAR2 - &VAR1) ge 5 then output;
else if &var2 ge 100 and (abs(&VAR2 - &VAR1)) / &VAR2 ge 0.05 then output;
run;
There is no need for macro code when you want to do conditional logic on data.
Macro code is for code generation.
See if this works for you
%LET VAR1 = JAN07;
%LET VAR2 = JAN06;
DATA HAVE;
INPUT NAME $ &var1 &var2;
DATALINES;
aaaaa 100 50
bbbbb 110 60
ccccc 20 15
ddddd 300 290
eeeee 80 79
fffff 115 130
;
RUN;
data want;
set have;
if &var1 lt 100 and abs(&VAR2 - &VAR1) ge 5 then output;
else if &var2 ge 100 and (abs(&VAR2 - &VAR1)) / &VAR2 ge 0.05 then output;
run;
The macro language statements are compiled (converted to text/SAS code) before the data step code is compiled and executed. So what you are doing will not work.
Instead, use the variable names in the macro strings to create valid SAS datastep code:
data WANT;
SET HAVE;
if &var2 LT 100 AND abs(&VAR2 - &VAR1) GE 5 then
output ;
else if abs(&VAR2 - &VAR1)/&VAR2 GE 0.05 then
output;
run;
I removed one of the conditions in the second IF statement, as that is already tested in the previous IF statement.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.