How to Filter by Row Number Using dplyr


You can use the following methods to filter a data frame by row number using the slice function from the dplyr 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.

Note: You can find the complete documentation for the slice function in dplyr here.

Additional Resources

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

How to Select Columns by Index Using dplyr
How to Select the First Row by Group Using dplyr
How to Filter by Multiple Conditions Using dplyr
How to Filter Rows that Contain a Certain String Using dplyr

Leave a Reply

Your email address will not be published.