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, ...) <- valueA vector with the values replaced.
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.
purrr::modify() family of functions.
(x <- rnorm(10))
#> [1] 2.0800399 0.2924207 -2.0576698 0.7170255 -0.6316115 1.2651173
#> [7] 0.1483972 -1.6832780 1.1883881 -1.4538138
### Replace elements of x that are < 1/4 with 0.
# Note that this code is pipeable.
x |> replace(`<`, 0, 1/4)
#> [1] 2.0800399 0.2924207 0.0000000 0.7170255 0.0000000 1.2651173 0.0000000
#> [8] 0.0000000 1.1883881 0.0000000
# More readable, using lambda notation.
x |> replace(\(.x) .x < 1/4, 0)
#> [1] 2.0800399 0.2924207 0.0000000 0.7170255 0.0000000 1.2651173 0.0000000
#> [8] 0.0000000 1.1883881 0.0000000
# 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)
#> [1] 2.0800399+0.0000000i 0.2924207+0.0000000i 0.0000000-2.0576698i
#> [4] 0.7170255+0.0000000i 0.0000000-0.6316115i 1.2651173+0.0000000i
#> [7] 0.1483972+0.0000000i 0.0000000-1.6832780i 1.1883881+0.0000000i
#> [10] 0.0000000-1.4538138i
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
#> [1] 2.0800399 0.2924207 0.0000000 0.7170255 0.0000000 1.2651173 0.0000000
#> [8] 0.0000000 1.1883881 0.0000000
stopifnot(identical(x, replace(y, `<`, 0, 1/4)))