View source: R/misc.utilities.R
| replace | R Documentation |
This is a thin wrapper around base::replace() that allows list
and/or values to be functions that are evaluated on x to obtain
the replacement indices and values. The assignment version replaces
x.
replace(x, list, values, ...)
replace(x, list, ...) <- value
x |
a vector. |
list |
either an index vector or a function (not a function name). |
values, value |
either a vector of replacement values or a function (not a function name). |
... |
additional arguments to |
list function is passed the whole vector x at once (not
elementwise) and any additional arguments to replace(), and must
return an indexing vector (numeric, logical, character,
etc.). values/value function is passed x after subsetting it by the
result of calling list().
If passing named arguments, x, list, and values may cause a
conflict.
A vector with the values replaced.
purrr::modify() family of functions.
(x <- rnorm(10))
### Replace elements of x that are < 1/4 with 0.
# Note that this code is pipeable.
x |> replace(`<`, 0, 1/4)
# More readable, using lambda notation.
x |> replace(\(.x) .x < 1/4, 0)
# base equivalent.
stopifnot(identical(replace(x, `<`, 0, 1/4),
base::replace(x, x < 1/4, 0)))
### Multiply negative elements of x by 1i.
x |> replace(\(.x) .x < 0, \(.x) .x * 1i)
stopifnot(identical(replace(x, \(.x) .x < 0, \(.x) .x * 1i),
base::replace(x, x < 0, x[x < 0] * 1i)))
### Modify the list in place.
y <- x
replace(x, `<`, 1/4) <- 0
x
stopifnot(identical(x, replace(y, `<`, 0, 1/4)))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.