In this tutorial, we will learn how to rename one or more columns of a dataframe in R. We will use rename() function in dplyr R package to change the name of a single column first and then see an example of using rename() function to rename more than one columns.
Let us get started by loading the packages needed.
library(tidyverse) library(palmerpenguins) packageVersion("dplyr")
We will use penguin dataset to show how to change the name of a column using rename() function.
penguins ## # A tibble: 344 × 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 ## 8 Adelie Torgersen 39.2 19.6 195 4675 ## 9 Adelie Torgersen 34.1 18.1 193 3475 ## 10 Adelie Torgersen 42 20.2 190 4250 ## # … with 334 more rows, and 2 more variables: sex <fct>, year <int>
rename a column names with rename() function dplyr
By using using new_name = old_name syntax with rename() function, we can change the name of a column. Here is example of changing a column name from “bill_length_mm” to “bill_length”
penguins %>% rename(bill_length = bill_length_mm) ## # A tibble: 344 × 8 ## species island bill_length bill_depth_mm flipper_length_… body_mass_g sex ## <fct> <fct> <dbl> <dbl> <int> <int> <fct> ## 1 Adelie Torgers… 39.1 18.7 181 3750 male ## 2 Adelie Torgers… 39.5 17.4 186 3800 fema… ## 3 Adelie Torgers… 40.3 18 195 3250 fema… ## 4 Adelie Torgers… NA NA NA NA <NA> ## 5 Adelie Torgers… 36.7 19.3 193 3450 fema… ## 6 Adelie Torgers… 39.3 20.6 190 3650 male ## 7 Adelie Torgers… 38.9 17.8 181 3625 fema… ## 8 Adelie Torgers… 39.2 19.6 195 4675 male ## 9 Adelie Torgers… 34.1 18.1 193 3475 <NA> ## 10 Adelie Torgers… 42 20.2 190 4250 <NA> ## # … with 334 more rows, and 1 more variable: year <int>
rename more than one column with rename() function dplyr
We can use rename() function to change the names of more than one column. Here we change the names of two variables using rename() function.
penguins %>% rename(bill_length=bill_length_mm, bill_depth=bill_depth_mm) ## # A tibble: 344 × 8 ## species island bill_length bill_depth flipper_length_mm body_mass_g sex ## <fct> <fct> <dbl> <dbl> <int> <int> <fct> ## 1 Adelie Torgersen 39.1 18.7 181 3750 male ## 2 Adelie Torgersen 39.5 17.4 186 3800 female ## 3 Adelie Torgersen 40.3 18 195 3250 female ## 4 Adelie Torgersen NA NA NA NA <NA> ## 5 Adelie Torgersen 36.7 19.3 193 3450 female ## 6 Adelie Torgersen 39.3 20.6 190 3650 male ## 7 Adelie Torgersen 38.9 17.8 181 3625 female ## 8 Adelie Torgersen 39.2 19.6 195 4675 male ## 9 Adelie Torgersen 34.1 18.1 193 3475 <NA> ## 10 Adelie Torgersen 42 20.2 190 4250 <NA> ## # … with 334 more rows, and 1 more variable: year <int>