To get the last observation of a dataset, you can use the end= data set option. end= creates a temporary numeric value whose value is used to detect the last observation.
data last_obs_only;
set all_data end=last_obs;
if last_obs;
run;
When working with datasets in any programming language, the ability to get snapshots of your data can be valuable for checking certain conditions.
One such case is if you want to get the last observation of a dataset in SAS.
To select the last observation of a dataset, you can use the end= data set option.
end= allows us to give a name to the last observation of a dataset. In the data step, we can check if we are on the last observation with an if statement and then output if we are there.
Below shows you a simple example of how you can select the last observation of a dataset in SAS.
data last_obs_only;
set all_data end=last_obs;
if last_obs;
run;
Get First Observation of Dataset in SAS
If you instead want to select the first observation of a dataset in SAS, use the SAS automatic variable _n_.
The SAS automatic variable _n_ represents the number of times the data step has iterated.
When a data step starts, _n_ is initialized to 1. Then, after each iteration through the data step, _n_ is incremented by one.
Therefore, we can use _n_ and check if _n_ is equal to 1. Then we can output those rows to a new dataset.
data first_obs;
set all_data;
if _n_ == 1;
run;
Hopefully this article has been useful for you to learn how to get the last observation of a SAS dataset.