How to count the number of observations in a SAS table?

Munichong picture Munichong · Oct 26, 2013 · Viewed 62.5k times · Source

I am very new to SAS. Now, I have a SAS data table as following:

    ID       score
-------------------
    01         1
    02         3
    03         4
    04         2

Is there any way to save the number of observations in this table using only PROC SORT and DATA step? I want to hold the value in the log window, which is like "hold N=4" in the SAS log script.

Sorry for my unprofessional description. Thanks in advance.

Answer

BellevueBob picture BellevueBob · Oct 27, 2013

As a new SAS user, the NOBS option may be all you need. However, as your coding skills increase, you may find yourself in situations where is is not appropriate. The NOBS option on the SET statement may not work in all cases. The value returned will be the number of physical observations in the data set, including any observations that may have been deleted in-place. It also may not work with certain views (especially views connected to external databases).

The "safest" way to find the number of undeleted observations in a data set or view is to use PROC SQL and actually count them, putting the result into a macro variable. For example, suppose you have a data object named HAVE:

proc sql noprint;
   select count(*) into : nobs
   from WORK.HAVE;
quit;
%put 'Obs in data set:' &nobs;

Note this works if HAVE is a data set or a view.

Alternatively, if you object is just a data set, you can use the SAS TABLES Dictionary view to return the NLOBS attribute, which has the number of "logical" observations (i.e. accounts for any deleted rows):

proc sql noprint;
   select nlobs into : nobs
   from dictionary.tables
   where libname='WORK'
    and memname='HAVE';
quit;
%put 'Obs in data set:' &nobs;

This will certainly be more efficient if your SAS data set is very large. I've often wondered why SAS does not make this NLOBS value available as an option on the SET statement, but I'm sure there are reasons.

PROC SQL, views, macro variables, and in-place deleted observations may be all new to you right now, but as you advance with your SAS learning you are bound to start using them.