How to Use _N_ in SAS (3 Examples)

The _N_ variable in SAS can be used to assign a sequential number to each observation stored in a SAS data set. This can be useful for tracking observations in a data set, or for creating groups of data. For example, _N_ can be used to count the number of observations, determine the number of observations in a group, or assign a unique identifier to each observation.


The _N_ automatic variable in SAS is used to count the number of loops of the data step.

Here are the most common ways to use _N_ in practice:

Method 1: Use _N_ to Select First Row in Dataset

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

Method 2: Use _N_ to Select First N Rows in Dataset

data new_data;
    set original_data;
    if _N_ <= 5 then output; /*select first 5 rows*/
run;

Method 3: Use _N_ to Add Row Numbers to Dataset

data new_data;
    set original_data;
    row_number = _N_;
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: Use _N_ to Select First Row in Dataset

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

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

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

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

Example 2: Use _N_ to Select First N Rows in Dataset

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

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

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

Example 3: Use _N_ to Add Row Numbers to Dataset

The following code shows how to use _N_ to add a column that displays row numbers for each row in the dataset:

/*create new dataset that contains column with row numbers*/
data new_data;
    set original_data;
    row_number = _N_;
run;

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

We can see that the new dataset has a column called row_number that contains the row number for each row in the dataset.

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

x