Learn R Programming

dat (version 0.5.0)

replace: Replace elements in a vector

Description

This function replaces elements in a vector. It is a link to replace as a generic function.

Usage

replace(x, ind, values, ...)

# S4 method for ANY,`function` replace(x, ind, values, ...)

# S4 method for ANY,formula replace(x, ind, values, ...)

# S4 method for ANY,character replace(x, ind, values, ...)

Arguments

x

(atomic | list) a vector.

ind

used as index for elements to be replaced. See details.

values

the values used for replacement.

...

arguments passed to ind if it can be interpreted as function. For a regex arguments are passed to grep.

Details

The idea is to provide a more flexible interface for the specification of the index. It can be a character, numeric, integer or logical which is then simply used in base::replace. It can be a regular expression in which case x should be named -- a character of length 1 and a leading "^" is interpreted as regex. When ind is a function (or formula) and x is a list then it should be a predicate function -- see the examples. When x is an atomic the function is applied on x and the result is used for subsetting.

Examples

Run this code
# NOT RUN {
replace(c(1, 2, NA), is.na, 0)
replace(c(1, 2, NA), rep(TRUE, 3), 0)
replace(c(1, 2, NA), 3, 0)
replace(list(x = 1, y = 2), "x", 0)
replace(list(x = 1, y = 2), "^x$", 0)
replace(list(x = 1, y = "a"), is.character, NULL)
# }

Run the code above in your browser using DataLab