Riyaz Iqbal
Riyaz Iqbal

Reputation: 71

SAS - How to get last 'n' observations from a dataset?

How can you create a SAS data set from another dataset using only the last n observations from original dataset. This is easy when you know the value of n. If I don't know 'n' how can this be done?

Upvotes: 7

Views: 18734

Answers (5)

subhro
subhro

Reputation: 171

You can achive this using the _nobs_ and _n_ variables. First, create a temporary variable to store the total no of obs. Then compare the automatic variable N to nobs.

data a;
set sashelp.class nobs=_nobs_;
if _N_ gt _nobs_ -5;
run;

Upvotes: 0

user1965813
user1965813

Reputation: 671

If the dataset is large, you might not want to read the whole dataset. Instead you could try a construction that reads the total number of Observations in the dataset first. So if you want to have the last of 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;

Upvotes: 4

Longfish
Longfish

Reputation: 7602

For the sake of variety, here's another approach (not necessarily a better one)

%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;

Upvotes: 2

BellevueBob
BellevueBob

Reputation: 9618

Using Joe's example of a macro variable to specify the number of observations you want, here is 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;

This should perform better since it only reads the specific observations you want.

Upvotes: 4

Joe
Joe

Reputation: 63424

This assumes you have a macro variable that says how many observations you want. NOBS tells you the number of observations in the dataset currently without reading the whole thing.

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

Upvotes: 8

Related Questions