BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
BrahmanandaRao
Lapis Lazuli | Level 10

Hi, 

Experts Good Morning

 

Here i  have a class dataset from that  i want to retrieve last three observations 

what if how many observations in a data set then how to get last three observations

 

/*if we do not know how many obs in a dataset then how we get last 3 records*/
data ds10;
do i=nobs to 1 ;
set sashelp.class point=i nobs=nobs;
output;
end;
stop;
run;

 

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Alternatively, with a subsetting if:

data ds10;
set sashelp.class nobs=nobs;
if _n_ > nobs - 3;
run;

With larger datasets and small subsets, the point= will perform better.

View solution in original post

8 REPLIES 8
BrahmanandaRao
Lapis Lazuli | Level 10
do i = nobs to 1 by -1;

just come reverse order only but i want last three records

and how to do unknown observations in a dataset

Kurt_Bremser
Super User

You already know the number of observations in the dataset (nobs). So just count up from nobs - 2, or don't use point= at all, and just output when _n_ reaches your threshold.

BrahmanandaRao
Lapis Lazuli | Level 10

Sorry not understand 

Kurt_Bremser
Super User

You know the total number of observations in your dataset (that's what the nobs= option does).

The automatic variable _N_ provided by SAS holds the number of data step iterations, so in a simple data step it gives you the number of the current observation read. By comparing _N_ to nobs - 3 in a subsetting if, you can achieve what you want.

BrahmanandaRao
Lapis Lazuli | Level 10

Sir 

Here it is correct output 

/*if we do not know how many obs in a dataset then how we get last 3 records*/
data ds10;
do i=nobs-2 to nobs;
set sashelp.class nobs=nobs point=i;
output;
end;
stop;
run;
Kurt_Bremser
Super User

Alternatively, with a subsetting if:

data ds10;
set sashelp.class nobs=nobs;
if _n_ > nobs - 3;
run;

With larger datasets and small subsets, the point= will perform better.

BrahmanandaRao
Lapis Lazuli | Level 10

Thank You sir

 

For your quick response and advise 

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 8 replies
  • 3470 views
  • 2 likes
  • 2 in conversation