R mutate_all() Function from dplyr

The mutate_all() function in R is used to apply a transformation to all columns in a data frame or tibble

This function is a scoped variant of mutate() and is especially handy for datasets where a uniform transformation needs to be applied to all columns.

Syntax

mutate_all(.tbl, .funs, ...)

Parameters

Name Description
.tbl It is a data frame or tibble to be transformed.
.funs This can be a single function or a list of functions to apply to the columns
Additional arguments passed to the function(s) specified in .funs.

Return value

It returns a modified data frame or tibble with each column transformed by the specified function(s).

Example 1: Applying a simple function

Basic understanding of R mutate_all() Function from dplyr

library(dplyr)

df <- data.frame(
  a = c(1, 2, 3),
  b = c(4, 5, 6),
  c = c(7, 8, 9)
)

df %>% mutate_all(~ . * 2)

Output

Output of applying a simple function

Example 2: Applying multiple functions

Figure of Applying multiple functions using dplyr mutate_all()

library(dplyr)

df <- data.frame(
  a = c(1, 2, 3),
  b = c(4, 5, 6),
  c = c(7, 8, 9)
)

# Apply multiple transformations
df %>% mutate_all(list(~ . * 2, ~ . + 1))

Output

Output of Applying multiple functions

Note:

As of dplyr 1.0.0 and later versions, these scoped mutation functions have been superseded by mutate() combined with across().

For instance, df %>% mutate(across(everything(), ~ . * 2)) achieves the same result as mutate_all(). The newer syntax is more consistent with the tidyverse’s approach to data manipulation.

Leave a Comment