Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataset

sas

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?

like image 774
Riyaz Iqbal Avatar asked Apr 23 '13 13:04

Riyaz Iqbal


2 Answers

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;
like image 109
Joe Avatar answered Sep 30 '22 00:09

Joe


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.

like image 30
BellevueBob Avatar answered Sep 30 '22 02:09

BellevueBob