01 / 20
NEW

mutate() &
Recoding

Learn to create new columns and recode values in your data frames using the dplyr package in R.

R Programming dplyr

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.

R
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 |>.

filter() select() mutate() summarize() arrange() ★ Today's focus

Why mutate() Matters

Derive New Data
Calculate BMI from height and weight, or compute profit from revenue minus cost.
Recode Categories
Turn numeric codes into meaningful labels like "Low", "Medium", "High".
Clean Data
Fix formats, handle NA values, standardize units: all with mutate().

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

R
data %>%
  mutate(
    new_column = expression,
    another_col = expression
  )
1
Pipe your data into mutate() using %>% or |>
2
Name the new column on the left side of =
3
Define the expression on the right: math, functions, or logic
4
Add multiple columns by separating with commas

How mutate() Transforms Data

INPUT name score "Alice" 85 "Bob" 92 "Cara" 78 mutate() OUTPUT name score grade "Alice" 85 "B" "Bob" 92 "A" "Cara" 78 "C" mutate ( grade = case_when ( score >= 90 ~ "A", score >= 80 ~ "B", TRUE ~ "C" ))

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()

1
Load dplyr: library(dplyr)
2
Inspect your data: Use glimpse(df) to see column names and types
3
Plan the new column: Decide the name and the expression (math, logic, or function)
4
Write the mutate(): Pipe data into mutate() with your expression
5
Save the result: Assign back with <- or chain more verbs

Example 1: Arithmetic Columns

R
# Calculate total and average scores
students %>%
  mutate(
    total   = math + english + science,
    average = total / 3
  )
namemathenglishsciencetotalaverage
Alice90858826387.7
Bob78928025083.3
Cara95889427792.3

Example 2: Recoding with if_else()

R
# Label students as pass or fail
students %>%
  mutate(
    result = if_else(
      average >= 80,
      "Pass",
      "Fail"
    )
  )
Syntax
if_else(condition, true_value, false_value)

Example 3: Recoding with case_when()

R
# 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()

R
# 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

R
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

✕ Forgetting to Save
mutate() returns a new data frame. If you don't assign it back with <-, the result is lost.
✕ Using = Instead of ==
Inside if_else() and case_when(), comparisons use ==. Single = is assignment.
✕ Wrong case_when() Order
Conditions are checked top-down. Putting >= 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?

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?