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 

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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
  • 8 replies
  • 2486 views
  • 2 likes
  • 2 in conversation