Hi,
I'm sure this is my fault but I don't know what's going wrong.
If you run the below code, the simple macro function will evaluate A - B into Y, and then do a dummy comparison.
%macro compare(a,b);
%let y=%sysevalf(&a-&b);
%put &a - &b = &y;
%if &y > 0 %then %do; %put hello; %end;
%mend compare;
%compare(5, 1); /* +ve (works) */
%compare(1, 5); /* -ve (works) */
%compare(5, 2.3); /* +ve decimal (works) */
%compare(2.3, 5); /* -ve decimal (doesn't work) */
For all four run-throughs the maths works fine (evidenced by the %put command), however the "%if &y > 0" line fails on the last run-through, when the result of the subtraction is both negative and a decimal.
I get this for the fourth run-through (in the log):
ERROR: A character operand was found in the %EVAL function or %IF condition where a numeric operand is required. The condition was: &y > 0
What on earth is happening!?
Use
%if %sysevalf(&y > 0,boolean) %then %do; %put hello; %end;
Macros are just text processors, they can get confused easily, and you have to take special care to make sure things work when performing arithmetic or Boolean comparisons.
Use
%if %sysevalf(&y > 0,boolean) %then %do; %put hello; %end;
Macros are just text processors, they can get confused easily, and you have to take special care to make sure things work when performing arithmetic or Boolean comparisons.
%macro compare(a,b);
%let y=%sysevalf(&a-&b);
%put &a - &b = &y;
%if %sysevalf(&y > 0) %then %do; %put hello; %end;
%else %put good bye;
%mend compare;
%compare(2.3, 5);
@EvoluZion3 wrote:%macro compare(a,b); %let y=%sysevalf(&a-&b); %put &a - &b = &y; %if &y > 0 %then %do; %put hello; %end; %mend compare; %compare(5, 1); /* +ve (works) */ %compare(1, 5); /* -ve (works) */ %compare(5, 2.3); /* +ve decimal (works) */ %compare(2.3, 5); /* -ve decimal (doesn't work) */
For all four run-throughs the maths works fine (evidenced by the %put command) ...
Note that without %SYSEVALF positive non-integers (more precisely: numbers involving a decimal point or other non-digit characters, including 1.0, 1E6, etc.) are compared as character strings. Change the %IF condition to &y > 10 and rerun the third macro call (after compiling the modified macro) to see that it's not maths that "works" here.
Without %SYSEVALF, such a "character string" after a minus sign (indicating that what follows is a number) is refused as a "character operand ... where a numeric operand is required" (see error message).
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.