I want to get observation number from expression <dsname(where=(...))> by using macro code. So I could write in any place (inside other procedure or %if statement) %if %sysfunc(nobs(dsname(where=(...)))) > 0 %then %do; BY-statement-code; %end;
My current solution uses PROC FCMP and DOSUBL inside custom function NOBS. After all I use %sysfunc(NOBS(...)). Inside NOBS function I use NOBS ATTRN to obtain answer if possible. Otherwise, inside DOSUBL I use PROC SQL to count observation number. Is there any other universal solution, which more stable than NLOBSF?
I think I could use FETCH inside NOBS function, but I don't know: should I extract WHERE= option and then apply something like If not where_string then delete; But there is a problem, that i can't in one function call extract where_string and use it as code.
DOSUBL seems very hard for performance. It's intitializes additional environment/space/memory?
Is there a way to do this elegantly and reliably?
What is your concern with using NLOBSF?
Years ago I was inspired by this paper by Jack Hamilton:
https://support.sas.com/resources/papers/proceedings/proceedings/sugi26/p095-26.pdf
And wrote a obscount macro, the core of which is to use NLOBS if SAS knows the number of records and there is no WHERE options, else use NLOBSF:
%if %sysfunc(attrn(&idnum, ANOBS)) and %sysfunc(attrn(&idnum, WHSTMT))=0 %then %do;
%*If sas knows number of obs, and there is no where statement, get nlobs;
%let nlobs = %sysfunc(attrn(&idnum,nlobs)); %*get number of obs;
%end;
%else %if %sysfunc(attrn(&idnum, ANOBS))=0
or (1<=%sysfunc(attrn(&idnum, WHSTMT)) and %sysfunc(attrn(&idnum, WHSTMT)) <=3) %then %do;
%*If sas doesnt know number of obs, or there is a where statement, get nlobsf (this iterates through dataset);
%let nlobs = %sysfunc(attrn(&idnum,nlobsf)); %*get number of obs;
%end;
Yes, DOSUBL is slow compared to most other functions, because it's doing a LOT of work (creating and destroying the side session to run execute the code).
Why not use FETCH ? Been using it for a LOOONG time.
https://github.com/sasutils/macros/blob/master/nobs.sas
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.