BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
VVDR
Obsidian | Level 7

Hi,

From a given SAS Dataset, how can I fetch last but one record or third record from the last without doing hard coding. I don't want to do hard coding the values as the number of observations keep on changing. 

 

TIA.

 

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

Hi @VVDR  Using SASHELP.CLASS dataset that has 19 records, here is an illustration-

The comments should make sense to you

/*last but one=numofrecs-1,third=last minus 2 records*/


data want;
/*last but one=numofrecs-1,third=last minus 2 records*/
 do _n_= nobs-1, nobs-2;
  set sashelp.class nobs=nobs point=_n_;
  output;
 end;
 stop;
run;

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20

Hi @VVDR  Using SASHELP.CLASS dataset that has 19 records, here is an illustration-

The comments should make sense to you

/*last but one=numofrecs-1,third=last minus 2 records*/


data want;
/*last but one=numofrecs-1,third=last minus 2 records*/
 do _n_= nobs-1, nobs-2;
  set sashelp.class nobs=nobs point=_n_;
  output;
 end;
 stop;
run;
Patrick
Opal | Level 21

Are these assignment questions?

 

Here one way to get what the question asked for. The code below selects the 3rd last column.

%let n_obs_from_last=3;
data want;
  obs=nobs -&n_obs_from_last +1;
  if obs>0 then
    do;
      set sashelp.class nobs=nobs point=obs;
      output;
    end;
  stop;
run;
Reeza
Super User
SAS supports indexing to allow for efficient data retrieval. If you need to extract records by varying criteria you may want to add in some indexes to support your queries.

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 973 views
  • 1 like
  • 4 in conversation