Rename

The function dplyr::rename() allows you to rename column names in a tibble.

Tidyverse reference page

Dataset

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 package
library("mgrtibbles")
#mammal_sleep_tbl tibble for demonstration
mammal_sleep_tbl<- mgrtibbles::mammal_sleep_tbl |> 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>

Rename columns

The format of the rename() function is:

dplyr(new_name=old_name)

Rename column total_sleep to tot_sleep.

mammal_sleep_tbl |> dplyr::rename(tot_sleep=total_sleep)
# A tibble: 5 × 11
  species   body_wt brain_wt non_dreaming dreaming tot_sleep life_span gestation
  <chr>       <dbl>    <dbl>        <dbl>    <dbl>     <dbl>     <dbl>     <dbl>
1 Africane… 6654      5.71           NA       NA         3.3      38.6       645
2 Africang…    1      0.0066          6.3      2         8.3       4.5        42
3 ArcticFox    3.38   0.0445         NA       NA        12.5      14          60
4 Arcticgr…    0.92   0.0057         NA       NA        16.5      NA          25
5 Asianele… 2547      4.60            2.1      1.8       3.9      69         624
# ℹ 3 more variables: predation <fct>, exposure <fct>, danger <fct>

Rename columns body_wt and brain_wt to body_kg and brain_kg.

mammal_sleep_tbl |> dplyr::rename(body_kg=body_wt, brain_kg=brain_wt)
# A tibble: 5 × 11
  species body_kg brain_kg 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>