mutate_cond: Mutate only rows of data.frame/tibble that satisfy condition

View source: R/zuluverse.R

mutate_condR Documentation

Mutate only rows of data.frame/tibble that satisfy condition

Description

The mutate_cond() function allows simple conditional mutations of data.frames by combining a conditional to select rows, followed by dplyr::mutate() syntax to specify how to change columns. This function is inspired by, and based on, a function proposed in a discussion on Stack Overflow. This function, however, extends the original mutate_cond() function proposed in that thread by falling back on using base::transform() if the dplyr package is not installed.

Usage

mutate_cond(
  .data,
  .condition,
  ...,
  .envir = parent.frame(),
  .method = c("default", "dplyr", "base")
)

Arguments

.data

The data.frame to mutate.

.condition

Conditional statement determining which rows to modify.

...

One or more statements determining which columns to mutate and how.

.envir

Which environment to use for evaluation.

.method

Which underlying method to use for the mutation. Acceptable values are:

  • "default", the default, uses dplyr::mutate() if available, but falls back on base::transform() (with a warning) if not.

  • "dplyr" uses dplyr::mutate() and throws an error if it is not available.

  • "base" always uses base::transform().

Details

All named parameters are prefixed with . to reduce the probability of conflict with the column names that are to be mutated, which are specified in the ... parameter.

The function relies on either dplyr::mutate() if available, or base::transform() if the dplyr package is available. Specifying multiple mutations in ... is allowed, but, if doing so, it is important to be aware of the differences between mutate() and transform(). The two functions are very similar, apart from the fact that mutate() executes the transformations in an iterative manner, so that later transformations can use the columns created by earlier transformations, whereas transform() uses the values from the original data.frame, regardless of the number of steps.

Examples

# Set dist to 3 where speed is 7 or less
result <- mutate_cond(cars, speed<=7, dist=3)
head(result)


torfason/zulutils documentation built on Aug. 21, 2023, 5:46 p.m.