Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

statistics

sas

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.

like image 325
Munichong Avatar asked Oct 26 '13 21:10

Munichong


1 Answers

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.

like image 156
BellevueBob Avatar answered Dec 03 '22 20:12

BellevueBob