library(tidyverse)
library(palmerpenguins)
data(penguins)dplyr::slice
Function of the Week
Select rows of dataset using row number
1 dplyr::slice()
In this document, I will introduce the slice() function and show what it’s for.
1.1 What is it for?
Say you want the first 7 rows of a table. Well, slice() is an easy way to do that. The slice() function accepts two arguments: The first is the dataset, and the second is the range of values you want to extract.
slice(penguins, 1:7)# A tibble: 7 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
7 Adelie Torgersen 38.9 17.8 181 3625
# ℹ 2 more variables: sex <fct>, year <int>
slice() is much more helpful in a tidy workflow, so you can see the first few rows of the data when you’re processing. This is really helpful when you’re building up a pipeline and need to show intermediate output without showing the entire table.
penguins %>%
slice(1:7)# A tibble: 7 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
7 Adelie Torgersen 38.9 17.8 181 3625
# ℹ 2 more variables: sex <fct>, year <int>
1.2 Is it helpful?
Yes, when you need to just show part of a table as an example, slice() can come in handy. I don’t use it everyday, but it can come in handy.