replace_if: Replace if

Description Usage Arguments Value Examples

View source: R/replace_if.R

Description

Takes a vector and replaces elements in the vector according to some condition. (Equivalent to something like df$var1[df$var2 == TRUE] <- 4 but less clunky.) Unlike the base function replace, replace_if allows replacement of NAs with some other value and only accepts scalar values as replacements (preventing recycling value errors). As with replace, this function does not work with factors; use forcats::fct_recode.

Usage

1
replace_if(var, condition, replacement)

Arguments

var

A variable.

condition

Either a scalar, a logical vector of the same length as var, or NA (in which case the function will look for and replace all NA values).

replacement

A scalar.

Value

var, replaced.

Examples

1
2
3
4
5
x <- c(1, 2, 3, 4)
replace_if(var = x, condition = x > 2, replacement = 99)

x <- c(1, 2, NA, 4)
replace_if(var = x, condition = NA, replacement = 99)

pewresearch/pewmethods documentation built on March 27, 2020, 7:22 p.m.