mutate( )

Add or transform columns in a data frame. mutate() is from the dplyr package, which is part of the tidyverse.

Required Library

install.packages("tidyverse")
library(tidyverse)

Syntax

# Pipe style
df %>% mutate(new_col = expression)

# Non-pipe style
mutate(df, new_col = expression)

df %>% mutate(new_col = expression) and mutate(df, new_col = expression) add a new column to a data frame. The expression on the right can reference any existing column by name.

# Pipe style
df %>% mutate(new_col = expression, another_col = expression)

# Non-pipe style
mutate(df, new_col = expression, another_col = expression)

df %>% mutate(col1 = ..., col2 = ...) and mutate(df, col1 = ..., col2 = ...) add multiple columns in a single call. Later expressions can reference columns created earlier in the same mutate().

Both versions do the same thing. With the pipe %>%, the data frame on the left is passed automatically as the first argument to mutate(). Without the pipe, you write that first argument explicitly as mutate(df, ...). Use whichever style is clearer for your workflow.

Store full-precision values in all columns. Apply signif() or round() only inside cat() when printing a final result. Rounding a column that feeds into later calculations accumulates error.

Examples

Add a new column

Original data

Add a new column

Add several columns at once
Use a column you just created

You can use a column you just created because mutate reads left to right.

A conditional column with if_else()

Argument Overview

Required arguments must be included when using a function while optional arguments can be included on demand.

.data data frame | tibble Required

The data frame to modify. In a pipe (%>% or %>%), this is passed automatically from the left-hand side — you do not write it explicitly.

# .data is passed automatically by the pipe:
capsules %>% mutate(fill_mass_mg = mass_filled_mg - mass_empty_mg)

Data Types: data.frame | tibble

— name–expression pairs name = expr Required

One or more expressions of the form new_column_name = expression. The right-hand side can reference any column in .data by name, and can also reference columns created earlier in the same mutate() call. Separate multiple expressions with commas.

mutate(
  fill_mass_mg = mass_filled_mg - mass_empty_mg,   # uses two existing columns
  ibu_mg       = fill_mass_mg * ibu_per_mg_powder  # references the column just created above
)

Data Types: any expression that returns a vector the same length as the data frame, or a single value (recycled to all rows)