BookmarkSubscribeRSS Feed
aviben
Calcite | Level 5

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

5 REPLIES 5
Jagadishkatam
Amethyst | Level 16

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
Robert_Bardos
Fluorite | Level 6

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

Jagadishkatam
Amethyst | Level 16

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

Regards,

Jag

Thanks,
Jag
Astounding
PROC Star

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.

Haikuo
Onyx | Level 15

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

Haikuo

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 5 replies
  • 726 views
  • 0 likes
  • 5 in conversation