To select the first 100 observations of a dataset in SAS, you can use the obs= data step set option and pass 100.

data first_100_obs;
    set all_data(obs=100);
run;

You can also use the SAS automatic variable _n_ to get the first 100 observations from a dataset.

data first_100_obs;
    set all_data;
    if _n_ <= 100 then output;
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 first 100 observations of a dataset in SAS.

The easiest way to create a new dataset with the first N observations of another dataset is with the obs= data step set option.

You can pass any number to obs=. In this case, if you want the first 100 observations, you pass 100.

Below shows a simple example of how you can use obs= in a data step to get the first 100 observations of a dataset in SAS.

data first_100_obs;
    set all_data(obs=100);
run;

Using _n_ to Select First 100 Observations of SAS Dataset

Another way you can select the first 100 observations of a dataset is with the help of 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 less than or equal to 100. Then we can output those rows to a new dataset.

Below shows you how you can use _n_ to select the first 100 observations of a SAS dataset.

data first_100_obs;
    set all_data;
    if _n_ <= 100 then output;
run;

How to Select Last Observation of Dataset in SAS

If you want to select the last observation of a SAS 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;

Hopefully this article has been useful for you to learn how to select the first 100 observations of a dataset in SAS.

Categorized in:

SAS,

Last Update: March 11, 2024