For demonstration we’ll load the mammal_sleep_tbl data from the mgrtibbles package (hyperlink includes install instructions). For easier viewing we’ll subset it so it only has 5 rows.
#Load packagelibrary("mgrtibbles")#mammal_sleep_tbl tibble for demonstrationmammal_sleep_tbl<- mgrtibbles::mammal_sleep_tbl |>#Slice to extract rows 1:5 dplyr::slice(1:5)mammal_sleep_tbl
# A tibble: 5 × 11
species body_wt brain_wt non_dreaming dreaming total_sleep life_span gestation
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Africa… 6654 5.71 NA NA 3.3 38.6 645
2 Africa… 1 0.0066 6.3 2 8.3 4.5 42
3 Arctic… 3.38 0.0445 NA NA 12.5 14 60
4 Arctic… 0.92 0.0057 NA NA 16.5 NA 25
5 Asiane… 2547 4.60 2.1 1.8 3.9 69 624
# ℹ 3 more variables: predation <fct>, exposure <fct>, danger <fct>
Relocate to first column
Relocating a column to the first column is the default behaviour of dplyr::relocate()
Relocate column “body_wt” to first column.
mammal_sleep_tbl |> dplyr::relocate(body_wt)
# A tibble: 5 × 11
body_wt species brain_wt non_dreaming dreaming total_sleep life_span gestation
<dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 6654 Africa… 5.71 NA NA 3.3 38.6 645
2 1 Africa… 0.0066 6.3 2 8.3 4.5 42
3 3.38 Arctic… 0.0445 NA NA 12.5 14 60
4 0.92 Arctic… 0.0057 NA NA 16.5 NA 25
5 2547 Asiane… 4.60 2.1 1.8 3.9 69 624
# ℹ 3 more variables: predation <fct>, exposure <fct>, danger <fct>
Relocate after another column
Relocate the body_wt column after the brain_wt column with the .after= option.
# A tibble: 5 × 11
species body_wt brain_wt dreaming non_dreaming total_sleep life_span gestation
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Africa… 6654 5.71 NA NA 3.3 38.6 645
2 Africa… 1 0.0066 2 6.3 8.3 4.5 42
3 Arctic… 3.38 0.0445 NA NA 12.5 14 60
4 Arctic… 0.92 0.0057 NA NA 16.5 NA 25
5 Asiane… 2547 4.60 1.8 2.1 3.9 69 624
# ℹ 3 more variables: predation <fct>, exposure <fct>, danger <fct>
Relocate a column to the last column
Use the last_col() helper function as the .after() option to move the predation column to the last column.
mammal_sleep_tbl |>#Select columns predation to danger dplyr::select(predation:danger) |>#Relocate predation to last column dplyr::relocate(predation, .after=last_col())
# A tibble: 5 × 11
species predation exposure danger body_wt brain_wt non_dreaming dreaming
<chr> <fct> <fct> <fct> <dbl> <dbl> <dbl> <dbl>
1 Africaneleph… 3 5 3 6654 5.71 NA NA
2 Africangiant… 3 1 3 1 0.0066 6.3 2
3 ArcticFox 1 1 1 3.38 0.0445 NA NA
4 Arcticground… 5 2 3 0.92 0.0057 NA NA
5 Asianelephant 3 5 4 2547 4.60 2.1 1.8
# ℹ 3 more variables: total_sleep <dbl>, life_span <dbl>, gestation <dbl>
Relocate all character (string) columns to the end.
mammal_sleep_tbl |>#Relocate string columns to end dplyr::relocate(where(is.character), .after=last_col()) |>#Select last five columns dplyr::select(last_col(4):last_col())