SAS data sets consist of a descriptor portion and a data portion that contains the data values. The descriptor portion of a SAS data set contains detailed information about the data set. This information includes:
Reading the descriptor portion is one of the most efficient and quickest ways of determining the number of observations in a SAS data set. Here are some examples:
/* SAS V9.x and higher */ data _NULL_; if 0 then set sashelp.class nobs=n; call symputx('nrows',n); stop; run; %put nobs=&nrows;
Many times users don't need to know how many obs there are, just whether there are any. In such cases, a data step like the following might be just what is needed. This technique also has the advantage that it works for views and other data sets where the number of observations is not available in the data set header (Don Henderson's tip from sascommunity.org).
data _null_; call symput('AnyObs','0'); /* set to 0 for No */ set &data(obs=1); call symput('AnyObs','1'); /* if got here there are obs so set to 1 for Yes */ run;
The metadata can also be accessed by the macro language using DATA step functions. The ATTRN function is used with the NLOBS argument in the %OBSCNT macro shown below to retrieve the number of non-deleted observations from the meta data.
%macro obscnt(dsn); %local nobs dsnid; %let nobs=.; %* Open the data set of interest; %let dsnid = %sysfunc(open(&dsn)); %* If the open was successful get the; %* number of observations and CLOSE &dsn; %if &dsnid %then %do; %let nobs=%sysfunc(attrn(&dsnid,nlobs)); %let rc =%sysfunc(close(&dsnid)); %end; %else %do; %put Unable to open &dsn - %sysfunc(sysmsg()); %end; %* Return the number of observations; &nobs %mend obscnt;
SAS dictionary tables can also be used to load the number of observations into a macro variable:
proc sql noprint; select nobs into :nobs separated by ' ' from dictionary.tables where libname='SASHELP' and memname='CLASS'; quit; %put TNote: nobs=&nobs;
Thanks to Alberto Negron and Tom Robinson for posting this help on sascommunity.org!
Registration is open! SAS is returning to Vegas for an AI and analytics experience like no other! Whether you're an executive, manager, end user or SAS partner, SAS Innovate is designed for everyone on your team. Register for just $495 by 12/31/2023.
If you are interested in speaking, there is still time to submit a session idea. More details are posted on the website.
Data Literacy is for all, even absolute beginners. Jump on board with this free e-learning and boost your career prospects.