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 mutate(): How to Add a Column in R

Updated

mutate() adds new columns to a data frame or changes the ones you already have. Every calculation in a data analysis, from percentages to labels, starts here.

What does mutate() do?

mutate() creates or changes columns. The number of rows stays the same, because each row gets its own new value. You write the new column name, an equals sign, and the calculation:

mutate(data, new_column = calculation)

With the pipe from the pipe operator lesson:

data |> mutate(new_column = calculation)

The new column is added at the right-hand end of the table unless you say otherwise. This lesson is part of our dplyr tutorial. To choose existing columns, see dplyr select, and to choose rows, see dplyr filter.

Sample data

We use the ten US cities again. To keep the output narrow, this table has five columns. Populations are rounded Census figures in thousands, for practice.

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"),
  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
citystateregionpopulation_2010population_2020
New YorkNYNortheast81758804
Los AngelesCAWest37933899
ChicagoILMidwest26962746
HoustonTXSouth20992305
PhoenixAZWest14461608
PhiladelphiaPANortheast15261604
San AntonioTXSouth13271435
San DiegoCAWest13071387
DallasTXSouth11981304
AustinTXSouth790962

Add your first column

Start with the simplest possible new column. Populations are in thousands. Let us add the 2020 population in millions, which is the number divided by 1000:

cities |> mutate(population_millions = population_2020 / 1000)

The name before = is the new column. The calculation after it can use any existing column. dplyr does the maths for every row at once:

citystateregionpopulation_2010population_2020population_millions
New YorkNYNortheast817588048.804
Los AngelesCAWest379338993.899
ChicagoILMidwest269627462.746
HoustonTXSouth209923052.305
PhoenixAZWest144616081.608
PhiladelphiaPANortheast152616041.604
San AntonioTXSouth132714351.435
San DiegoCAWest130713871.387
DallasTXSouth119813041.304
AustinTXSouth7909620.962

That is how you add a column in R with dplyr. The original cities is not changed. If you want to keep the new column, assign the result back:

cities <- cities |> mutate(population_millions = population_2020 / 1000)

For the rest of this lesson, we leave cities as it was above so that every example starts from the same table.

Calculate with existing columns

You can use any arithmetic operator: +, -, *, / and ^. How many more people lived in each city in 2020 than in 2010?

cities |> mutate(growth = population_2020 - population_2010)
citystateregionpopulation_2010population_2020growth
New YorkNYNortheast81758804629
Los AngelesCAWest37933899106
ChicagoILMidwest2696274650
HoustonTXSouth20992305206
PhoenixAZWest14461608162
PhiladelphiaPANortheast1526160478
San AntonioTXSouth13271435108
San DiegoCAWest1307138780
DallasTXSouth11981304106
AustinTXSouth790962172

The growth column is in thousands too. Austin gained 172 thousand people, and Chicago just 50 thousand.

Create multiple columns

To mutate multiple columns, add several named calculations to the same call, separated by commas. Later ones can use columns created earlier in the same mutate():

cities |> mutate(
  growth     = population_2020 - population_2010,
  growth_pct = round(growth / population_2010 * 100, 1)
)
citystateregionpopulation_2010population_2020growthgrowth_pct
New YorkNYNortheast817588046297.7
Los AngelesCAWest379338991062.8
ChicagoILMidwest26962746501.9
HoustonTXSouth209923052069.8
PhoenixAZWest1446160816211.2
PhiladelphiaPANortheast15261604785.1
San AntonioTXSouth132714351088.1
San DiegoCAWest13071387806.1
DallasTXSouth119813041068.8
AustinTXSouth79096217221.8

The second line uses growth, which was only created on the line above. round(x, 1) rounds to one decimal place. Austin grew by 21.8%, the fastest of the ten. Put one column per line, as above, so that the code is easy to read.

To apply the same calculation to many columns, across() saves typing. It has its own lesson: dplyr across.

Create text columns

Columns can hold text. paste() joins pieces together, and sep sets what goes between them:

cities |> mutate(label = paste(city, state, sep = ", "))
citystatelabel
New YorkNYNew York, NY
Los AngelesCALos Angeles, CA
ChicagoILChicago, IL
HoustonTXHouston, TX
PhoenixAZPhoenix, AZ
PhiladelphiaPAPhiladelphia, PA
San AntonioTXSan Antonio, TX
San DiegoCASan Diego, CA
DallasTXDallas, TX
AustinTXAustin, TX

The related paste0() joins with no separator at all. This is handy for building labels such as paste0(city, " (", state, ")").

A single value, such as a country name, is repeated for every row:

cities |> mutate(country = "USA")
citystatecountry
New YorkNYUSA
Los AngelesCAUSA
ChicagoILUSA
HoustonTXUSA
PhoenixAZUSA
PhiladelphiaPAUSA
San AntonioTXUSA
San DiegoCAUSA
DallasTXUSA
AustinTXUSA

Create TRUE/FALSE columns

A comparison such as state == "TX" gives TRUE or FALSE for each row. Storing it as a column makes it easy to count or filter later:

cities |> mutate(is_texas = state == "TX")
citystateis_texas
New YorkNYFALSE
Los AngelesCAFALSE
ChicagoILFALSE
HoustonTXTRUE
PhoenixAZFALSE
PhiladelphiaPAFALSE
San AntonioTXTRUE
San DiegoCAFALSE
DallasTXTRUE
AustinTXTRUE

Conditions work the same way as inside filter(), so everything from the dplyr filter lesson can be used here.

mutate() with if_else()

Often you want a column that depends on a condition, like "large" or "mid-size". Use if_else(condition, value_if_true, value_if_false). This is the dplyr version of the ifelse function in base R:

cities |> mutate(size = if_else(population_2020 > 2000, "large", "mid-size"))
citypopulation_2020size
New York8804large
Los Angeles3899large
Chicago2746large
Houston2305large
Phoenix1608mid-size
Philadelphia1604mid-size
San Antonio1435mid-size
San Diego1387mid-size
Dallas1304mid-size
Austin962mid-size

Cities above 2,000 thousand are "large", and all the rest are "mid-size". if_else() is stricter than base ifelse(): both outcomes must be the same type, so you catch mistakes early. When you need three or more outcomes, nested if_else() calls get messy. Use dplyr case_when instead.

Use a column summary

A calculation can include a single value computed from the whole column, such as an average. That one value is reused for every row. Here is how far each city is from the average 2020 population (2605.4 thousand):

cities |> mutate(diff_from_avg = population_2020 - mean(population_2020))
citypopulation_2020diff_from_avg
New York88046198.6
Los Angeles38991293.6
Chicago2746140.6
Houston2305-300.4
Phoenix1608-997.4
Philadelphia1604-1001.4
San Antonio1435-1170.4
San Diego1387-1218.4
Dallas1304-1301.4
Austin962-1643.4

New York is far above average, and Austin is well below it. If a column contains missing values, mean() returns NA. Use mean(x, na.rm = TRUE) in that case.

Change or remove a column

If the name on the left already exists, mutate() replaces that column rather than adding one. Make the city names upper case:

cities |> mutate(city = toupper(city))
citystateregion
NEW YORKNYNortheast
LOS ANGELESCAWest
CHICAGOILMidwest
HOUSTONTXSouth
PHOENIXAZWest
PHILADELPHIAPANortheast
SAN ANTONIOTXSouth
SAN DIEGOCAWest
DALLASTXSouth
AUSTINTXSouth

Replacing is the way to convert units, fix types, or clean text. To remove a column, set it to NULL:

cities |> mutate(region = NULL)
citystatepopulation_2010population_2020
New YorkNY81758804
Los AngelesCA37933899
ChicagoIL26962746
HoustonTX20992305
PhoenixAZ14461608
PhiladelphiaPA15261604
San AntonioTX13271435
San DiegoCA13071387
DallasTX11981304
AustinTX790962

For dropping columns, select(-region) is more common and reads more clearly.

Choose where the column goes

By default, new columns are added at the end. Use .before or .after to place them. Both accept a column name or position:

cities |> mutate(growth = population_2020 - population_2010, .after = city)
citygrowthstateregionpopulation_2010population_2020
New York629NYNortheast81758804
Los Angeles106CAWest37933899
Chicago50ILMidwest26962746
Houston206TXSouth20992305
Phoenix162AZWest14461608
Philadelphia78PANortheast15261604
San Antonio108TXSouth13271435
San Diego80CAWest13071387
Dallas106TXSouth11981304
Austin172TXSouth790962

The growth column now sits right after city. You can also write .before = population_2010, or .before = 1 to make it the first column.

Control which columns are kept

The .keep argument decides which existing columns appear in the result:

.keep =Result
"all" (default)All original columns plus the new ones
"used"New columns, plus the original columns that were used to build them
"unused"New columns, plus original columns that were not used
"none"Only the new columns
cities |> mutate(growth = population_2020 - population_2010, .keep = "used")
population_2010population_2020growth
81758804629
37933899106
2696274650
20992305206
14461608162
1526160478
13271435108
1307138780
11981304106
790962172

Only the two population columns, which were used in the calculation, remain, plus growth.

transmute()

transmute() works like mutate() but keeps only the columns you create or name. It is a shortcut for mutate(..., .keep = "none"):

cities |> transmute(city, growth = population_2020 - population_2010)
citygrowth
New York629
Los Angeles106
Chicago50
Houston206
Phoenix162
Philadelphia78
San Antonio108
San Diego80
Dallas106
Austin172

Here city is listed on its own, so it is kept. Everything not mentioned is dropped. Use transmute() when you want a small, tidy result, and mutate() when you want to keep the full table.

mutate() within groups

Normally a column summary uses the whole table. Since dplyr 1.1.0, the .by argument calculates it separately for each group. This adds the total 2020 population of each city's region:

cities |> mutate(region_total = sum(population_2020), .by = region)
cityregionpopulation_2020region_total
New YorkNortheast880410408
Los AngelesWest38996894
ChicagoMidwest27462746
HoustonSouth23056006
PhoenixWest16086894
PhiladelphiaNortheast160410408
San AntonioSouth14356006
San DiegoWest13876894
DallasSouth13046006
AustinSouth9626006

Every row keeps its place, and each city gets the total for its own region. This differs from summarise(), which would collapse each region into a single row. Grouping is covered in dplyr group_by and summarise.

mutate() in a pipeline

Here is a realistic sequence. Which cities grew by more than 8%, and by how much? First create the growth percentage, then filter, then tidy up and sort:

cities |>
  mutate(growth_pct = round((population_2020 - population_2010) / population_2010 * 100, 1)) |>
  filter(growth_pct > 8) |>
  select(city, state, growth_pct) |>
  arrange(desc(growth_pct))
citystategrowth_pct
AustinTX21.8
PhoenixAZ11.2
HoustonTX9.8
DallasTX8.8
San AntonioTX8.1

Order matters. filter() can only use growth_pct because mutate() created it earlier in the chain. The arrange() step is covered in the dplyr arrange lesson.

dplyr mutate vs base R

TaskdplyrBase R
Add a columnmutate(cities, growth = population_2020 - population_2010)cities$growth <- cities$population_2020 - cities$population_2010
Add several columnsmutate(cities, a = ..., b = ...)transform(cities, a = ..., b = ...)
Conditional columnmutate(cities, size = if_else(x > 2000, "large", "mid-size"))cities$size <- ifelse(cities$x > 2000, "large", "mid-size")
Remove a columnmutate(cities, region = NULL)cities$region <- NULL

The base R assignment cities$growth <- ... changes the data frame in place. mutate() never does. It returns a copy, which makes pipelines safer.

Common mistakes

MistakeWhat happensFix
Not saving the resultThe column shows in the output but cities is unchangedAssign it: cities <- cities |> mutate(...)
mutate(growth <- a - b)You get a column with a strange name instead of growthUse = inside mutate()
mutate(growth = cities$a - cities$b)Works for simple cases, but breaks with grouping or after a filterWrite the column names bare: a - b
Supplying a vector of the wrong lengthError that says it can't recycle a value to the table size (wording varies by version)Give one value, or exactly one value per row
if_else() with mixed typesError: the true and false values cannot be combinedMake both values the same type, for example both text
Using a new column before it existsError: object not foundCreate it in an earlier mutate() or earlier in the same call
Averages come out as NAThe column has missing valuesUse na.rm = TRUE

Practice exercises

Use the five-column cities table. Try each one before opening the answer.

Exercise 1

Add a column growth that holds the 2020 population minus the 2010 population.

Show answer
cities |> mutate(growth = population_2020 - population_2010)
citystateregionpopulation_2010population_2020growth
New YorkNYNortheast81758804629
Los AngelesCAWest37933899106
ChicagoILMidwest2696274650
HoustonTXSouth20992305206
PhoenixAZWest14461608162
PhiladelphiaPANortheast1526160478
San AntonioTXSouth13271435108
San DiegoCAWest1307138780
DallasTXSouth11981304106
AustinTXSouth790962172

Exercise 2

Add a column label that looks like "Austin (TX)".

Show answer
cities |> mutate(label = paste0(city, " (", state, ")"))
citystatelabel
New YorkNYNew York (NY)
Los AngelesCALos Angeles (CA)
ChicagoILChicago (IL)
HoustonTXHouston (TX)
PhoenixAZPhoenix (AZ)
PhiladelphiaPAPhiladelphia (PA)
San AntonioTXSan Antonio (TX)
San DiegoCASan Diego (CA)
DallasTXDallas (TX)
AustinTXAustin (TX)

Exercise 3

Add a column fast_growth that says "yes" if the 2020 population is more than 8% above 2010, and "no" otherwise.

Show answer
cities |>
  mutate(fast_growth = if_else(population_2020 > population_2010 * 1.08, "yes", "no"))
citypopulation_2010population_2020fast_growth
New York81758804no
Los Angeles37933899no
Chicago26962746no
Houston20992305yes
Phoenix14461608yes
Philadelphia15261604no
San Antonio13271435yes
San Diego13071387no
Dallas11981304yes
Austin790962yes

Exercise 4

Return only city and a new growth column, using transmute().

Show answer
cities |> transmute(city, growth = population_2020 - population_2010)
citygrowth
New York629
Los Angeles106
Chicago50
Houston206
Phoenix162
Philadelphia78
San Antonio108
San Diego80
Dallas106
Austin172

Exercise 5

Add a column region_max that holds the largest 2020 population in each city's region.

Show answer
cities |> mutate(region_max = max(population_2020), .by = region)
cityregionpopulation_2020region_max
New YorkNortheast88048804
Los AngelesWest38993899
ChicagoMidwest27462746
HoustonSouth23052305
PhoenixWest16083899
PhiladelphiaNortheast16048804
San AntonioSouth14352305
San DiegoWest13873899
DallasSouth13042305
AustinSouth9622305

dplyr FAQ

How do I add a new column in R with dplyr?

Use mutate() with the new column name on the left of an equals sign and the calculation on the right, for example mutate(cities, growth = population_2020 - population_2010).

What is the difference between mutate() and transmute()?

mutate() keeps all existing columns and adds the new ones. transmute() keeps only the columns you create or name, and drops the rest.

How do I create multiple columns at once in dplyr?

List them in one mutate() call, separated by commas. Later columns can use earlier ones created in the same call.

Does mutate() change the original data frame?

No. It returns a new data frame. Assign the result with <- if you want to keep it.

How do I use if else inside mutate()?

Use if_else(condition, value_if_true, value_if_false) inside mutate(). For more than two outcomes, use case_when().

How do I delete a column with mutate()?

Set it to NULL, for example mutate(cities, region = NULL). The select() function with a minus sign does the same job.

Key points

  • mutate(new_name = calculation) adds a column. The row count stays the same.
  • Put several columns in one call, and later ones can use earlier ones.
  • Using an existing name replaces that column. Setting a column to NULL removes it.
  • Use if_else() for two outcomes and case_when() for more.
  • .before, .after and .keep control column position and which columns remain.
  • transmute() keeps only the new columns. .by computes group-wise values without collapsing rows.
  • The result is a new table. Assign it with <- to keep it.

Next, learn to sort rows with dplyr arrange. For a refresher on picking rows, see dplyr filter.