18 C
London
Thursday, July 24, 2025
HomeSASData Munging in SASHow to Select the First N Rows of a Dataset in SAS

How to Select the First N Rows of a Dataset in SAS

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Here are the two most common ways to select the first N rows from a dataset in SAS:

Method 1: Select First Row

data first_row;
    set original_data;
    if _N_ = 1 then output;
run;

Method 2: Select First N Rows

data first_N_rows;
    set original_data;
    if _N_ 5 then output; /*select first 5 rows*/
run;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $ points rebounds;
    datalines;
Warriors 25 8
Wizards 18 12
Rockets 22 6
Celtics 24 11
Thunder 27 14
Spurs 33 19
Nets 31 20
Mavericks 34 10
Kings 22 11
Pelicans 39 23
;
run;

/*view dataset*/
proc print data=original_data;

Example 1: Select First Row

The following code shows how to select just the first row of the dataset:

/*create new dataset that contains only the first row*/
data first_row;
    set original_data;
    if _N_ = 1 then output;
run;

/*view new dataset*/
proc print data=first_row;

We can see that the new dataset contains only the first row of the original dataset.

Example 2: Select First N Rows

The following code shows how to select the first five rows of the dataset:

/*create new dataset that contains first 5 rows of original dataset*/
data first_N_rows;
    set original_data;
    if _N_ 5 then output;
run;

/*view new dataset*/
proc print data=first_N_rows;

We can see that the new dataset contains only the first five rows of the original dataset.

To select a different number of starting rows, simply change the value after _N_ in the code above.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Use Proc Summary in SAS
How to Use Proc Tabulate in SAS
How to Rename Variables in SAS
How to Create New Variables in SAS

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories