The rename() Function in R


The rename() function in R can help you rename columns in a data frame. It uses using new_name = old_name syntax. It is important to note that rename() isn’t a built-in function that comes with default R installations. It belongs to the tidyverse collection, or to be more exact, the dplyr package.

> # simple rename() example in R
> df <- data.frame(col1 = c("bob", "sally", "jennifer"), col2 = c("Smith", "Johnson", "Jackson"))
> df
      col1    col2
1      bob   Smith
2    sally Johnson
3 jennifer Jackson
> df2 <- rename(df, "FirstName" = "col1")   # change col1 to FirstName
> df2
  FirstName    col2
1       bob   Smith
2     sally Johnson
3  jennifer Jackson

As a comparison, here is the syntax for renaming a column in SQL: ALTER TABLE table_name RENAME COLUMN old_name to new_name;.

Leave a Reply