replace: Replace values in a vector according to functions

View source: R/misc.utilities.R

replaceR Documentation

Replace values in a vector according to functions

Description

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.

Usage

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.

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.

Value

A vector with the values replaced.

See Also

purrr::modify() family of functions.

Examples


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


statnet/statnet.common documentation built on June 9, 2025, 2:34 a.m.