How to Use the slice() Function in dplyr (With Examples)


You can use the slice() function from the dplyr package in R to subset rows based on their integer locations.

You can use the following methods to subset certain rows in a data frame:

Method 1: Subset One Specific Row

#get row 3 only
df %>% slice(3)

Method 2: Subset Several Rows

#get rows 2, 5, and 6
df %>% slice(2, 5, 6)

Method 3: Subset A Range of Rows

#get rows 1 through 3
df %>% slice(1:3)

Method 4: Subset Rows by Group

#get first row by group
df %>%
  group_by(var1) %>%
  slice(1)

The following examples show how to each method with the following data frame:

#create dataset
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'C', 'C'),
                 points=c(1, 2, 3, 4, 5, 6, 7),
                 assists=c(1, 5, 2, 3, 2, 2, 0))

#view dataset
df

  team points assists
1    A      1       1
2    A      2       5
3    A      3       2
4    B      4       3
5    B      5       2
6    C      6       2
7    C      7       0

Example 1: Subset One Specific Row

The following code shows how to use the slice() function to select only row 3 in the data frame:

#get row 3 only
df %>% slice(3)

  team points assists
1    A      3       2

Example 2: Subset Several Rows

The following code shows how to use the slice() function to select several specific rows in the data frame:

#get rows 2, 5, and 6
df %>% slice(2, 5, 6)

  team points assists
1    A      2       5
2    B      5       2
3    C      6       2

Example 3: Subset A Range of Rows

The following code shows how to use the slice() function to select all rows in the range 1 through 3:

#get rows 1 through 3
df %>% slice(1:3)

  team points assists
1    A      1       1
2    A      2       5
3    A      3       2

Example 4: Subset Rows by Group

The following code shows how to use the slice() function to select the first row in certain groups:

#get first row by group
df %>%
  group_by(team) %>%
  slice(1)

# A tibble: 3 x 3
# Groups:   team [3]
  team  points assists
       
1 A          1       1
2 B          4       3
3 C          6       2

Additional Resources

The following tutorials explain how to perform other common functions using dplyr:

How to Remove Rows Using dplyr
How to Arrange Rows Using dplyr
How to Filter by Multiple Conditions Using dplyr

Leave a Reply

Your email address will not be published.