Learn R Programming

tidytable (version 0.10.2)

mutate: Add/modify/delete columns

Description

With mutate() you can do 3 things:

  • Add new columns

  • Modify existing columns

  • Delete columns

Usage

mutate(
  .df,
  ...,
  .by = NULL,
  .keep = c("all", "used", "unused", "none"),
  .before = NULL,
  .after = NULL
)

Arguments

.df

A data.frame or data.table

...

Columns to add/modify

.by

Columns to group by

.keep

experimental: This is an experimental argument that allows you to control which columns from .df are retained in the output:

  • "all", the default, retains all variables.

  • "used" keeps any variables used to make new variables; it's useful for checking your work as it displays inputs and outputs side-by-side.

  • "unused" keeps only existing variables not used to make new variables.

  • "none", only keeps grouping keys (like transmute()).

.before, .after

Optionally indicate where new columns should be placed. Defaults to the right side of the data frame.

Examples

Run this code
df <- data.table(
  a = 1:3,
  b = 4:6,
  c = c("a", "a", "b")
)

df %>%
  mutate(double_a = a * 2,
         a_plus_b = a + b)

df %>%
  mutate(double_a = a * 2,
         avg_a = mean(a),
         .by = c)

df %>%
  mutate(double_a = a * 2, .keep = "used")

df %>%
  mutate(double_a = a * 2, .after = a)

Run the code above in your browser using DataLab