Description Usage Arguments Value Examples
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
.
1 | replace_if(var, condition, replacement)
|
var |
A variable. |
condition |
Either a scalar, a logical vector of the same length as |
replacement |
A scalar. |
var
, replaced.
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)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.