How to Filter by Row Number Using dplyr

Using dplyr, you can filter by row number by using the filter function and specifying the appropriate row number. For example, the code filter(df, row_number() == 5) will filter the data frame df to include only the fifth row. Additionally, you can use the slice function to filter a range of rows within the data frame. For example, the code slice(df, c(2,6)) will filter the data frame df to include only rows 2 through 6.


You can use the following methods to filter a data frame by row number using the slice function from the package:

Method 1: Filter by Specific Row Numbers

df %>% slice(2, 3, 8)

This will return row numbers 2, 3, and 8.

Method 2: Filter by Range of Row Numbers

df %>% slice(2:5)

This will return rows 2 through 5.

The following examples show how to use each method in practice with the following data frame in R:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'),
                 points=c(10, 10, 8, 6, 15, 15, 12, 12),
                 rebounds=c(8, 8, 4, 3, 10, 11, 7, 7))

#view data frame
df

  team points rebounds
1    A     10        8
2    B     10        8
3    C      8        4
4    D      6        3
5    E     15       10
6    F     15       11
7    G     12        7
8    H     12        7

Example 1: Filter by Specific Row Numbers

We can use the following code to filter for rows 2, 3, and 8:

library(dplyr)

#filter for only rows 2, 3, and 8
df %>% slice(2, 3, 8)

  team points rebounds
1    B     10        8
2    C      8        4
3    H     12        7

Notice that only rows 2, 3, and 8 are returned from the original data frame.

Example 2: Filter By Range of Row Numbers

We can use the following code to filter for rows between 2 and 5:

library(dplyr)

#filter for rows between 2 and 5
df %>% slice(2:5)

  team points rebounds
1    B     10        8
2    C      8        4
3    D      6        3
4    E     15       10

Notice that only the rows between 2 and 5 are returned from the original data frame.

The following tutorials explain how to perform other common operations in dplyr:

x