R mutate_if() Function from dplyr

The mutate_if() function in R is used for the conditional transformation of columns in a data frame or tibble. It applies a specified function to each column that meets a specific condition.

This function allows you to selectively mutate columns based on a predicate, which is a function that returns TRUE or FALSE.

Columns for which the predicate returns TRUE are transformed using the specified function.

Syntax

mutate_if(.tbl, .predicate, .funs, ...)

Parameters

Name Description
.tbl It is a data frame or tibble to be transformed
.predicate A predicate function that returns TRUE or FALSE for each column. Columns for which this function returns TRUE are mutated.
.funs Functions to apply to each selected column.
Additional arguments passed to the function(s) specified in .funs.

Return value

It returns a modified data frame or tibble with transformations applied to the selected columns.

Example 1: Mutating numeric columns

Understanding of R mutate_if() Function from dplyr

library(dplyr)

df <- data.frame(
  a = c(1, 2, 3),
  b = c("A", "B", "C"),
  c = c(7, 8, 9)
)

# Multiply all numeric columns by 2
df %>% mutate_if(is.numeric, ~ . * 2)

Output

Output of Mutating numeric columns

Example 2: Applying multiple functions to selected columns

Applying multiple functions to selected columns

library(dplyr)

df <- data.frame(
  a = c(1, 2, 3),
  b = c("A", "B", "C"),
  c = c(7, 8, 9)
)

# Multiply all numeric columns by 2
df %>% mutate_if(is.numeric, list(~ . + 1, ~ . * 2))

Output

Output of Applying multiple functions to selected columns using mutate_if()

This method is helpful for datasets where you need to apply transformations to columns based on their characteristics.

Note:

As of dplyr 1.0.0 and later versions, the use of mutate_if() has been superseded by mutate() in combination with an across() function.

For example, df %>% mutate(across(where(is.numeric), ~ . * 2)) is the modern equivalent of using mutate_if() for mutating numeric columns.

Leave a Comment