Coding

How to Rename a Column in R (Base R and dplyr)

To rename a column in R with base R, assign to the data frame's names: names(df)[names(df) == "old_name"] <- "new_name". With dplyr, use rename(df, new_name = old_name), where the new name goes on the left.

The examples below use the built-in iris data frame, whose columns are Sepal.Length, Sepal.Width, Petal.Length, Petal.Width and Species. Both approaches work on any data frame, and the dplyr ones also work on tibbles.

Rename a column in base R by name

A data frame's column names live in its names attribute. You read them with names(df) and replace them with names(df) <- value. To change one column without touching the others, find its position by name and assign to just that element:

df <- iris
names(df)[names(df) == "Petal.Length"] <- "petal_length"
names(df)

Example output:

[1] "Sepal.Length" "Sepal.Width"  "petal_length" "Petal.Width"  "Species"

The expression names(df) == "Petal.Length" produces a logical vector with TRUE in the matching position. Assigning to names(df)[...] replaces only that element. If the old name does not exist, the logical vector is all FALSE and nothing changes, with no error. That silent no-op is the main trap of this method, so print names(df) afterwards when it matters.

Rename a column by position

If you know the column's position, index the names directly:

names(df)[3] <- "petal_length"

This is short, but it breaks quietly if the column order changes later, for example when a data source adds a column at the front. Prefer matching by name in scripts you will run again.

colnames() or names()?

You will see both in tutorials. For a data frame they are equivalent: colnames(df) <- c(...) works, but the R documentation states that for a data frame, colnames eventually calls names, "but the latter are preferred". For a matrix there is no names attribute for columns, so use colnames() there:

m <- cbind(1, 1:4)
colnames(m) <- c("x", "Y")

The same documentation page recommends column names that are unique and syntactically valid. A name such as Unit Price is allowed, but you have to quote it with backticks every time you use it with $, so a name like unit_price is easier to live with.

Rename several columns at once in base R

To rename a chosen set of columns, match the old names to positions with match(), so the order of your lookup does not matter:

old <- c("Petal.Length", "Sepal.Length")
new <- c("petal_length", "sepal_length")
names(df)[match(old, names(df))] <- new

If one of the old names is missing, match() returns NA for it, so the assignment will not do what you intended. Check the names first with all(old %in% names(df)) if the data comes from outside your control.

To change every column name with one rule, assign the result of a string function to the whole vector. This replaces the dots with underscores and lowercases everything:

names(df) <- tolower(gsub(".", "_", names(df), fixed = TRUE))

Use fixed = TRUE here. Without it, . is a regular expression that matches any character, and every name would turn into underscores.

Whole-vector assignment has one more edge case. The documentation says that if the new value is shorter than the object, "it is extended by character NAs to the length of x". Assigning only two names to a five-column data frame therefore leaves three columns named NA, instead of raising an error. Always supply one name per column, or use the indexed form above.

Rename a column with dplyr

The dplyr package (part of the tidyverse) has a function made for this. Install it once with install.packages("dplyr"), then load it:

library(dplyr)
rename(iris, petal_length = Petal.Length)

The documented form is rename(.data, ...), and in the dots you write new_name = old_name. Rows, column order and any grouping are kept, and the result is a new data frame, so assign it if you want to keep it. Several columns go in one call, separated by commas:

df <- rename(iris,
  petal_length = Petal.Length,
  sepal_length = Sepal.Length
)

In a pipeline, with the native pipe (R 4.1 or later) or the magrittr pipe:

df <- iris |> rename(petal_length = Petal.Length)
df <- iris %>% rename(petal_length = Petal.Length)

If the old name has a space, wrap it in backticks: rename(df, price = `Unit Price`).

Rename from a lookup vector

When the renames are stored in a named vector, with the new names as the vector's names and the old names as its values, pass it through all_of(). This example is from the dplyr documentation:

lookup <- c(pl = "Petal.Length", sl = "Sepal.Length")
rename(iris, all_of(lookup))

The documentation explains the difference between the two helpers. all_of() raises an error if a name in the lookup is not in the data. any_of() ignores missing names, which suits files whose columns vary between exports:

rename(iris, any_of(lookup))

Rename many columns with a function: rename_with()

rename_with(.data, .fn, .cols = everything(), ...) applies a function to the column names. The function must return a character vector with the same length as its input. By default it touches every column, and the third argument restricts it:

rename_with(iris, toupper)
rename_with(iris, toupper, starts_with("Petal"))
rename_with(iris, ~ tolower(gsub(".", "_", .x, fixed = TRUE)))

The first line uppercases all five names. The second changes only Petal.Length and Petal.Width. The third turns every name into lowercase with underscores, the same result as the base R one-liner above, written with a formula where .x stands for the vector of selected names.

One documented pitfall: if your function uses paste0() and the selection might be empty, set recycle0 = TRUE inside the paste0() call, or the empty selection raises an error.

Which method should you use?

TaskBase Rdplyr
One column, by namenames(df)[names(df) == "a"] <- "b"rename(df, b = a)
One column, by positionnames(df)[3] <- "b"Use the column's name instead
Missing old nameSilently does nothingError with all_of(), ignored with any_of()
All names, by a rulenames(df) <- tolower(names(df))rename_with(df, tolower)
Extra package neededNoYes (dplyr)

Use base R when the script should have no dependencies, or when you are inside a small helper function. Use dplyr when the data is already moving through a pipeline, or when you want all_of() to stop on a misspelled name. Both give the same result for a plain rename.

If the rename does not work

  • Error that the column cannot be found in dplyr. Check the order: rename(df, new = old), not the reverse. Also check capitalisation, since R names are case-sensitive.
  • Nothing changed. You did not assign the result. rename(df, ...) on its own prints a new data frame and leaves df unchanged.
  • Columns named NA after a base R rename. The replacement vector was shorter than the number of columns. Print length(names(df)) and compare.
  • A function named rename from another package. If another loaded package masks rename, call it as dplyr::rename().

Once your columns have clean names, loops over them are easy to write. See For loop in R: syntax, seq_along, next and break examples.

Frequently asked questions

What is the difference between names() and colnames() for a data frame?
For a data frame they do the same job. The R documentation says that colnames eventually calls names for a data frame, and that names is the preferred function. For a matrix, only colnames works, because a matrix stores column names in its dimnames.
Does dplyr rename() change the original data frame?
No. rename() returns a new data frame and leaves the input as it was. To keep the change, assign the result, for example df <- rename(df, new_name = old_name).
Why does rename() put the new name on the left?
dplyr uses the form new_name = old_name, the same order as an assignment. If you write the old name first, the call will not do what you intended, so check the order when a rename fails.
How do I rename a column that has a space in its name?
Wrap the old name in backticks inside dplyr, for example rename(df, price = `Unit Price`). In base R, use a quoted string: names(df)[names(df) == "Unit Price"] <- "price".
How do I rename only some columns using a function?
Use rename_with() with a second selection argument, for example rename_with(df, toupper, starts_with("Petal")). Only the selected columns are passed to the function.

Sources