mutate() &
Recoding
Learn to create new columns and recode values in your data frames using the dplyr package in R.
What is mutate()?
mutate() is a function from the dplyr package that adds new columns to a data frame or modifies existing ones. It never removes columns: it only creates or transforms them.
mutate(data, new_col = expression)
The dplyr Pipeline
mutate() is one of five core dplyr verbs. Each verb does one thing well, and you chain them together using the pipe operator %>% or |>.
Why mutate() Matters
Real-world data rarely comes in the exact form you need. mutate() is the tool that bridges the gap between raw data and analysis-ready data.
The mutate() Syntax
data %>% mutate( new_column = expression, another_col = expression )
How mutate() Transforms Data
mutate() vs transmute()
| mutate() | transmute() | |
|---|---|---|
| Keeps existing columns? | ✓ Yes | ✕ No |
| Returns | All columns + new | Only new columns |
| Use case | Enrich the data frame | Extract computed values |
| Number of rows | Same as input | Same as input |
How to Apply mutate()
library(dplyr)glimpse(df) to see column names and types<- or chain more verbsExample 1: Arithmetic Columns
# Calculate total and average scores students %>% mutate( total = math + english + science, average = total / 3 )
| name | math | english | science | total | average |
|---|---|---|---|---|---|
| Alice | 90 | 85 | 88 | 263 | 87.7 |
| Bob | 78 | 92 | 80 | 250 | 83.3 |
| Cara | 95 | 88 | 94 | 277 | 92.3 |
Example 2: Recoding with if_else()
# Label students as pass or fail students %>% mutate( result = if_else( average >= 80, "Pass", "Fail" ) )
if_else(condition, true_value, false_value)
Example 3: Recoding with case_when()
# Assign letter grades with multiple conditions students %>% mutate( grade = case_when( average >= 90 ~ "A", average >= 80 ~ "B", average >= 70 ~ "C", TRUE ~ "F" ) )
if_else() vs case_when()
| if_else() | case_when() | |
|---|---|---|
| Number of outcomes | Exactly 2 | Many (2+) |
| Syntax style | condition, true, false | condition ~ value |
| Best for | Binary: yes/no, pass/fail | Multiple categories (A/B/C/D/F) |
| Default value | The FALSE argument | TRUE ~ value |
| Nesting needed? | Yes, for 3+ outcomes | No: flat structure |
Recoding with recode()
# Replace coded values with labels survey %>% mutate( satisfaction = recode(rating, `1` = "Very Low", `2` = "Low", `3` = "Medium", `4` = "High", `5` = "Very High" ) )
Chaining Multiple Transformations
weather %>% mutate( # Convert Fahrenheit to Celsius temp_c = (temp_f - 32) * 5 / 9, # Label the temperature feeling = case_when( temp_c >= 30 ~ "Hot", temp_c >= 15 ~ "Mild", TRUE ~ "Cold" ), # Round the Celsius value temp_c = round(temp_c, 1) )
Common Mistakes
<-, the result is lost.==. Single = is assignment.>= 70 before >= 90 means no one gets an "A".Recoding Toolkit Summary
| Function | Best For | Example Use |
|---|---|---|
| if_else() | Binary split (2 outcomes) | Pass / Fail |
| case_when() | Multiple categories (3+) | Letter grades A-F |
| recode() | Direct value mapping | 1 → "Low", 2 → "High" |
| Arithmetic | Numeric transformations | BMI, totals, averages |
| round() / log() | Math functions inside mutate | Rounding, log-transform |
Question 1 of 5
What does mutate() do to the original columns in your data frame?
Question 2 of 5
Which function should you use inside mutate() to assign a letter grade ("A", "B", "C", "D", "F") based on a numeric score?
Question 3 of 5
What does the line TRUE ~ "Other" do at the end of a case_when() block?
TRUE ~ "Other" is the catch-all default. Since TRUE is always true, any row that did not match an earlier condition falls through to this line and gets the value "Other".Question 4 of 5
What is wrong with this code?
df %>% mutate(status = if_else(score > 50, "High", "Low"))
Question 5 of 5
In a single mutate() call, can a new column reference another new column defined above it in the same call?
transform() function.