dplyr Tutorial

Clean, transform and summarise data with dplyr

Practical lessons on filter, mutate, group_by, joins and more — with sample data and exercises.

dplyr cheat sheet Get help with your data

dplyr rename(): How to Rename Columns in R

Updated

Use dplyr rename() to give columns clearer names while keeping every row and all other columns. Start with one column, then learn multiple-column renaming, rename_with(), and advanced data-cleaning workflows.

What does rename() do in R?

rename() is a function from the dplyr package that changes column names in a data frame or tibble. It is useful when imported data has unclear headings, abbreviations, inconsistent naming conventions, or names that are difficult to use in an analysis.

For example, a column called population_2020 might be easier to work with as population if the dataset only contains one population measure. Renaming columns makes code easier to read and helps communicate what each variable represents.

rename(data, new_name = old_name)

Remember the direction: new name on the left, existing name on the right. The old column must already exist in the data. The function keeps the column's values, its position, all other columns, and all rows unchanged.

Important: rename() changes names, not data values. To create a new calculated column, use dplyr mutate(). To choose which columns to keep, use dplyr select().

Sample data used in the examples

The examples use a small dataset of ten US cities. The population figures are rounded Census values in thousands, included here for practice. First, create the data frame and load dplyr:

library(dplyr)

cities <- tibble(
  city = c("New York", "Los Angeles", "Chicago", "Houston", "Phoenix",
           "Philadelphia", "San Antonio", "San Diego", "Dallas", "Austin"),
  state = c("NY", "CA", "IL", "TX", "AZ", "PA", "TX", "CA", "TX", "TX"),
  region = c("Northeast", "West", "Midwest", "South", "West",
             "Northeast", "South", "West", "South", "South"),
  time_zone = c("Eastern", "Pacific", "Central", "Central", "Mountain",
                "Eastern", "Central", "Pacific", "Central", "Central"),
  population_2010 = c(8175, 3793, 2696, 2099, 1446, 1526, 1327, 1307, 1198, 790),
  population_2020 = c(8804, 3899, 2746, 2305, 1608, 1604, 1435, 1387, 1304, 962)
)
cities: the original column names
citystateregiontime_zonepopulation_2010population_2020
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
HoustonTXSouthCentral20992305
PhoenixAZWestMountain14461608
PhiladelphiaPANortheastEastern15261604
San AntonioTXSouthCentral13271435
San DiegoCAWestPacific13071387
DallasTXSouthCentral11981304
AustinTXSouthCentral790962

Inspect the column names at any time with names(cities). This is a helpful first step when you are unsure how a column is spelled.

names(cities)
[1] "city" "state" "region" "time_zone" "population_2010" "population_2020"

1. Rename one column in R

The simplest way to rename a column in R with dplyr is to write the new name, an equals sign, and then the current name. Suppose you want to change population_2020 to population:

cities |>
  rename(population = population_2020)
The population_2020 column is now called population
citystateregiontime_zonepopulation_2010population
New YorkNYNortheastEastern81758804
Los AngelesCAWestPacific37933899
ChicagoILMidwestCentral26962746
HoustonTXSouthCentral20992305
PhoenixAZWestMountain14461608

Notice that the column's values have not changed. The name alone has changed, and the other columns remain in the result. In dplyr, you do not put the old column name in quotation marks for this standard form.

Understand the rename() syntax

The basic syntax is:

rename(data, new_name = old_name)
  • data is the data frame or tibble you want to work with.
  • new_name is the name you want the column to have.
  • old_name is the column name that currently exists in the data.

For example, rename(cities, city_name = city) changes city to city_name. Writing rename(cities, city = city_name) would do the opposite: it expects a column called city_name to exist already.

2. Rename multiple columns at the same time

You can rename several columns in one call by separating each assignment with a comma. This is useful when a dataset has abbreviated or unclear column headings.

cities |>
  rename(
    city_name = city,
    state_code = state,
    population = population_2020
  )
Renaming multiple columns
city_namestate_coderegiontime_zonepopulation_2010population
New YorkNYNortheastEastern8175
Los AngelesCAWestPacific3793
ChicagoILMidwestCentral2696
HoustonTXSouthCentral2099
PhoenixAZWestMountain1446

Renaming several columns together keeps the transformation in one clear place. This is particularly useful when preparing imported survey data, sales files, or research datasets for analysis.

3. Save the renamed data frame

By itself, rename() returns a renamed version of the data. If you run it without assigning the result, the original object cities remains unchanged. To keep the new names, assign the result to an object:

cities_clean <- cities |>
  rename(
    city_name = city,
    state_code = state,
    population = population_2020
  )

names(cities_clean)

Use cities_clean for later steps and keep cities as the original data. This approach is helpful when cleaning data because it preserves a reference to the unmodified input.

You can also replace the original object deliberately:

cities <- cities |>
  rename(population = population_2020)

Only do this when you intend to use the new names in subsequent code.

4. Use rename() with the R pipe operator

The pipe operator |> passes the data on its left into the next function. This makes a sequence of cleaning steps easier to read. If you are new to pipes, see the dplyr pipe operator tutorial.

cities |>
  rename(
    city_name = city,
    state_code = state,
    population = population_2020
  ) |>
  filter(state_code == "TX") |>
  arrange(desc(population))

This pipeline renames the columns, keeps cities in Texas, and sorts them by the renamed population column from largest to smallest. After renaming a column, use its new name in all later steps of the same pipeline.

# A tibble: 4 × 6
  city_name    state_code region time_zone population_2010 population
  Houston      TX         South  Central              2099       2305
  San Antonio  TX         South  Central              1327       1435
  Dallas       TX         South  Central              1198       1304
  Austin       TX         South  Central               790        962

The exact printed formatting can differ by tibble and dplyr version, but the rows and ordering are determined by the code.

5. Rename columns with rename_with()

Use rename_with() when you want to apply a function to column names rather than manually specify every new name. It is especially useful for large datasets with many columns. The basic syntax is:

rename_with(data, function_to_apply)

For example, convert every column name to lowercase:

cities |>
  rename_with(tolower)

The current sample already uses lowercase names, so the visible result is unchanged. The function becomes more useful when imported column names contain capital letters, such as City, State, and Population.

Here is a small example with mixed-case names:

survey <- tibble(
  RespondentID = c(101, 102, 103),
  AgeGroup = c("18-24", "25-34", "18-24"),
  MonthlyIncome = c(1800, 2400, 2100)
)

survey |> rename_with(tolower)
# A tibble: 3 × 3
  respondentid agegroup monthlyincome
          101   18-24          1800
          102   25-34          2400
          103   18-24          2100

Note that tolower() changes case but does not add underscores. The next examples show how to apply other name-cleaning functions.

6. Change column names to uppercase, lowercase, or title case

Convert all column names to lowercase

survey |>
  rename_with(tolower)

Lowercase names are common in R projects because they are consistent and easy to type.

Convert all column names to uppercase

survey |>
  rename_with(toupper)

This changes names such as RespondentID to RESPONDENTID. Uppercase names are sometimes used for identifiers or when matching an existing data standard.

Make only selected names lowercase

The .cols argument lets you choose which columns are affected. For example, to lowercase names that begin with a capital letter is not a separate selection rule; you can instead select columns explicitly or use a helper:

survey |>
  rename_with(tolower, .cols = c(RespondentID, AgeGroup))

Here, MonthlyIncome remains unchanged while the two selected names are converted to lowercase.

7. Add or remove prefixes and suffixes from column names

Data imported from multiple sources often contains systematic names such as old_population_2010, old_population_2020, or sales_total_raw. With rename_with(), a string function can standardise many names at once.

Add a prefix to every column

cities |>
  rename_with(~ paste0("citydata_", .x))

The .x represents the existing column name. For example, city becomes citydata_city.

Add a suffix to every column

cities |>
  rename_with(~ paste0(.x, "_raw"))

This turns city into city_raw and population_2020 into population_2020_raw. Suffixes can help distinguish raw variables from cleaned or derived variables.

Remove a known prefix

prefixed <- tibble(
  raw_city = c("Austin", "Dallas"),
  raw_state = c("TX", "TX"),
  raw_population = c(962, 1304)
)

prefixed |>
  rename_with(~ sub("^raw_", "", .x))

The regular expression ^raw_ matches raw_ only at the beginning of a name, so it is removed while the rest of each name is preserved.

Replace spaces and punctuation in names

For a quick example, replace spaces with underscores:

messy <- data.frame(
  "City Name" = c("Austin", "Dallas"),
  "Population 2020" = c(962, 1304),
  check.names = FALSE
)

messy |>
  rename_with(~ gsub(" ", "_", .x, fixed = TRUE))

This creates names such as City_Name and Population_2020. For more comprehensive name cleaning, including consistent case and punctuation, consider a dedicated function such as janitor::clean_names() from the janitor package.

8. Rename only selected columns

By default, rename_with() applies its function to all column names. Use .cols to limit the change to a subset. For example, standardise only the population columns:

cities |>
  rename_with(tolower, .cols = starts_with("population"))

This particular example does not visibly change the names because they are already lowercase, but the selection pattern is useful for mixed-case datasets. You can also use helpers such as ends_with(), contains(), and where() when they fit your naming or data-type requirements.

To rename a selected column explicitly, use rename() instead:

cities |>
  rename(city_name = city)

Use rename() when you know the exact new name. Use rename_with() when the same transformation should be applied to a set of names.

9. Rename columns using names stored in variables

Sometimes you receive column names from a configuration file, a function argument, or a user-selected option. If you store the old and new names as character strings, use tidyselect's all_of() helper with rename() to map the names carefully.

For example, suppose a column called city should be renamed to city_name based on a character vector:

old_name <- "city"
new_name <- "city_name"

# Create a named character vector:
rename_map <- c(city_name = "city")

cities |>
  rename(all_of(rename_map))

The named vector has the new name on the left and the old name as its value. This pattern is useful for reusable data-cleaning functions. Confirm the exact naming map before applying it to important data.

Advanced note: When programming reusable functions, dplyr also supports tidy evaluation for column names supplied as function arguments. For many everyday tasks, explicitly naming the columns in rename() is simpler and easier to maintain.

10. dplyr rename() vs base R

You can rename columns without dplyr, using base R's names() or colnames(). Both approaches are valid. The best choice depends on whether you are working in a dplyr pipeline or making a direct change to a data frame.

TaskdplyrBase R
Rename one columnrename(cities, city_name = city)names(cities)[names(cities) == "city"] <- "city_name"
Rename multiple columnsrename(cities, city_name = city, state_code = state)Assign replacements to matching positions in names()
Make all names lowercaserename_with(cities, tolower)names(cities) <- tolower(names(cities))
Inspect namesnames(cities)names(cities)

With base R, assigning to names(cities) changes the object directly. By contrast, dplyr's rename() returns a modified data frame, which is commonly passed along a pipe or saved to a new object.

11. Common rename() errors and how to fix them

ProblemLikely reasonWhat to do
Column doesn't existThe old name is misspelled or uses different capitalisation.Run names(data) and copy the exact existing name.
New and old names are reversedThe syntax was written as old_name = new_name.Use new_name = old_name.
The original object still has old namesThe returned result was not assigned.Use data <- data |> rename(new = old) or save to a new object.
rename() is not foundThe dplyr package is not loaded.Run library(dplyr) or use dplyr::rename().
Names are still inconsistent after renamingOnly the explicitly named columns were changed.Use rename_with() to apply a consistent rule across many columns.
Later pipeline step failsThe code refers to an old name after it has been renamed.Use the new name in all subsequent pipeline steps.

When troubleshooting, start by checking the object and its names:

glimpse(cities)
names(cities)

Also check the spelling and capitalisation of every old name. R column names are case-sensitive, so City and city are different names.

12. Practice exercises

Use the original cities data frame created above. Try to write each expression before revealing the answer.

Exercise 1: Rename one column

Rename city to city_name.

Show answer
cities |>
  rename(city_name = city)

Exercise 2: Rename two columns

Rename state to state_code and population_2020 to population.

Show answer
cities |>
  rename(
    state_code = state,
    population = population_2020
  )

Exercise 3: Save a cleaned data frame

Rename city to city_name and save the result as cities_clean.

Show answer
cities_clean <- cities |>
  rename(city_name = city)

Exercise 4: Convert every column name to lowercase

Use rename_with() to make all column names lowercase.

Show answer
cities |>
  rename_with(tolower)

Exercise 5: Rename, filter, and sort

Rename population_2020 to population, keep only cities in Texas, and sort by population from largest to smallest.

Show answer
cities |>
  rename(population = population_2020) |>
  filter(state == "TX") |>
  arrange(desc(population))

dplyr FAQ

How do I rename a column in R using dplyr?

Use rename(data, new_name = old_name). For example, cities |> rename(population = population_2020) renames population_2020 to population.

How do I rename multiple columns in dplyr?

List each new name and its existing name separated by commas, for example rename(cities, city_name = city, state_code = state).

Does rename() change the original data frame?

No. rename() returns a renamed data frame. Assign the result back to the same object, such as cities <- cities |> rename(city_name = city), if you want to replace the original object.

What is the difference between rename() and rename_with()?

rename() lets you specify the new name for each selected column. rename_with() applies a function to column names, making it useful for standardising many names at once.

How do I rename every column in R?

Use rename_with() with a function that transforms names, such as rename_with(cities, tolower) to make all column names lowercase.

Why does rename() say a column does not exist?

The old column name may be misspelled, have different capitalisation, or have been changed earlier in the pipeline. Check names(data) or glimpse(data) before renaming.

Key points about renaming columns in R

  • Use dplyr::rename() to rename columns while keeping their values and the rest of the data frame.
  • The syntax is new_name = old_name—the new name comes first.
  • Rename multiple columns by separating assignments with commas.
  • Assign the result if you want to keep the renamed data frame.
  • Use rename_with() to apply a function such as tolower() or toupper() to column names.
  • Use base R's names() when you want to change or inspect names directly.

Renaming columns is a small but important part of preparing data for analysis. Once your column names are clear and consistent, continue with dplyr select() to choose columns, dplyr mutate() to create new variables, and dplyr filter() to select rows. These functions work especially well together in a readable data-cleaning pipeline.