Resolving numeric condition

Reply
New Contributor
Posts: 4

Resolving numeric condition

Hello,

Certainly a trivial question: how do I put an %if condition with numeric criteria? For example, I want the code to process if the number of obs in a dataset is greater than 6

%if &nbObs>6 %then %do;

     ....         

%end;

The problem is that &nbObs resolve to "23" which resolve incorrectly the condition. Tried with %eval without success

Thanks

Trusted Advisor
Posts: 1,128

Re: Resolving numeric condition

Hi,

did you try to create the macro variable using proc sql, this will create the numeric macro variable with the number of observations. please try the below code

proc sql;

     select count(*) into : obs from dataset_name;

quit;

%put &obs;

Thanks,

Jag

Thanks,
Jag
Frequent Contributor
Posts: 106

Re: Resolving numeric condition

Jag is right insofar as you should try to get an unquoted (ie. numeric) value for &nbObs.

There is a solution however even when &nbObs has the value (quotes being part of the value)  "23"

  %if  %eval ( %sysfunc(dequote(&nbObs)) > 6 ) %then %do ;

This first removes the quotes from &nbObs and then does the %eval part.

But as mentioned initially (giving credit to Jag): try to get a pure numeric value for &nbObs first.

Regards

Robert

Trusted Advisor
Posts: 1,128

Re: Resolving numeric condition

Thank you Robert, yes indeed your solution is also very useful.

Regards,

Jag

Thanks,
Jag
Super User
Posts: 5,069

Re: Resolving numeric condition

Although I'm not able to test it at the moment, you could probably get rid of %eval from the earlier suggestion:

%if %sysfunc(dequote(&nobs)) > 6 %then %do;

One thing you should NOT do is add double quotes to match:

%if &nobs > "6" %then %do;

It will run, but will make the wrong comparison.  Because of the double quotes, it will make a character comparison.  Since 2 < 6, the comparison will be false.

Better yet, listen to the suggestions to get rid of the double quotes from &nobs and you won't have to worry about complicated comparisons.

Respected Advisor
Posts: 3,124

Re: Resolving numeric condition

Agree with Astounding. %if will automatically conduct  %eval operation at the background.

Haikuo

Ask a Question
Discussion stats
  • 5 replies
  • 275 views
  • 0 likes
  • 5 in conversation