SAS - How to get the latest "n" observations from a dataset?

How can you create a SAS dataset from another dataset using only the last n observations from the original dataset. This is easy when you know the value of n. If I do not know "n", how can this be done?

+5
source share
4 answers

This assumes that you have a macro variable that indicates how many observations you want. NOBS tells you the number of observations in the dataset at present, without reading all of this.

%let obswant=5;
data want;
set sashelp.class nobs=obscount;
if _n_ gt (obscount-&obswant.);
run;
+8
source

Using Joe's macro example to indicate how many observations you need, here's another answer:

%let obswant = 10;
data want;
   do _i_=nobs-(&obswant-1) to nobs;
      set have point=_i_ nobs=nobs;
      output;
      end;
   stop;  /* Needed to stop data step */
run;

, , .

+4

If the data set is large, you may not need to read the entire data set. Instead, you can try a construct that first reads the total number of observations in the dataset. Therefore, if you want to get the latest observations:

data t;
  input x;
datalines;
1
2
3
4
;

%let dsid=%sysfunc(open(t));
%let num=%sysfunc(attrn(&dsid,nlobs));
%let rc=%sysfunc(close(&dsid));
%let number = 2;

data tt;
set t (firstobs =  %eval(&num.-&number.+1));
run;
+2
source

For a change, here's a different approach (not necessarily the best)

%let obswant=5;

proc sql noprint;
select nlobs-&obswant.+1 into :obscalc
from dictionary.tables
where libname='SASHELP' and upcase(memname)='CLASS';
quit;

data want;
set sashelp.class (firstobs=&obscalc.);
run;
+1
source

All Articles