For demonstration we’ll load the knz_bison data from the lterdatasampler package (hyperlink includes install instructions).
#Load packagelibrary("lterdatasampler")#knz_bison tibble for demonstrationbison_tbl <- lterdatasampler::knz_bison |>#Convert to tibble tibble::as_tibble()bison_tbl
# A tibble: 8,325 × 8
data_code rec_year rec_month rec_day animal_code animal_sex animal_weight
<chr> <dbl> <dbl> <dbl> <chr> <chr> <dbl>
1 CBH01 1994 11 8 813 F 890
2 CBH01 1994 11 8 834 F 1074
3 CBH01 1994 11 8 B-301 F 1060
4 CBH01 1994 11 8 B-402 F 989
5 CBH01 1994 11 8 B-403 F 1062
6 CBH01 1994 11 8 B-502 F 978
7 CBH01 1994 11 8 B-503 F 1068
8 CBH01 1994 11 8 B-504 F 1024
9 CBH01 1994 11 8 B-601 F 978
10 CBH01 1994 11 8 B-602 F 1188
# ℹ 8,315 more rows
# ℹ 1 more variable: animal_yob <dbl>
Slice
The base slice() function is incredibly similar to normal indexing of a tibble/data.frame. Its main advantage is that it can be more easily used with pipes.
Extract rows 1 to 5.
bison_tbl |> dplyr::slice(1:5)
# A tibble: 5 × 8
data_code rec_year rec_month rec_day animal_code animal_sex animal_weight
<chr> <dbl> <dbl> <dbl> <chr> <chr> <dbl>
1 CBH01 1994 11 8 813 F 890
2 CBH01 1994 11 8 834 F 1074
3 CBH01 1994 11 8 B-301 F 1060
4 CBH01 1994 11 8 B-402 F 989
5 CBH01 1994 11 8 B-403 F 1062
# ℹ 1 more variable: animal_yob <dbl>
Head and tail
Extract the first 6 rows.
bison_tbl |> dplyr::slice_head(n=6)
# A tibble: 6 × 8
data_code rec_year rec_month rec_day animal_code animal_sex animal_weight
<chr> <dbl> <dbl> <dbl> <chr> <chr> <dbl>
1 CBH01 1994 11 8 813 F 890
2 CBH01 1994 11 8 834 F 1074
3 CBH01 1994 11 8 B-301 F 1060
4 CBH01 1994 11 8 B-402 F 989
5 CBH01 1994 11 8 B-403 F 1062
6 CBH01 1994 11 8 B-502 F 978
# ℹ 1 more variable: animal_yob <dbl>
Extract the last 4 rows.
bison_tbl |> dplyr::slice_tail(n=4)
# A tibble: 4 × 8
data_code rec_year rec_month rec_day animal_code animal_sex animal_weight
<chr> <dbl> <dbl> <dbl> <chr> <chr> <dbl>
1 CBH01 2020 10 29 P-080 F 330
2 CBH01 2020 10 29 P-081 M 350
3 CBH01 2020 10 29 P-082 F 265
4 CBH01 2020 10 29 P-083 M 370
# ℹ 1 more variable: animal_yob <dbl>
Max and min
Extract the 3 observations with the highest animal_weight.