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

Arguments

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 if it is a function; otherwise ignored.

Value

A vector with the values replaced.

Details

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.

See also

purrr::modify() family of functions.

Examples


(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)))