(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)))
Run the code above in your browser using DataLab