Table of Contents
To select the first N rows of a dataset in SAS, you can use the firstobs= and obs= options in a SET statement. The firstobs= option specifies the first row to be read and the obs= option specifies how many rows to read from the dataset. For example, to select the first 10 rows of a dataset, you would use the SET statement with the firstobs=1 and obs=10 options.
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;
To select a different number of starting rows, simply change the value after _N_ in the code above.
The following tutorials explain how to perform other common tasks in SAS: