Learn R Programming

container (version 1.0.5)

replace: Replace Values in Containers Safely

Description

Try to find and replace elements and signal an error if not found, unless it is stated to explicitly add the element (see option add).

Usage

replace(.x, ...)

ref_replace(.x, ...)

# S3 method for Container replace(.x, old, new, add = FALSE, ...)

# S3 method for Container ref_replace(.x, old, new, add = FALSE, ...)

# S3 method for Dict replace(.x, old, new, ...)

# S3 method for Dict ref_replace(.x, old, new, ...)

Value

For Container, an object of class Container (or one of the respective derived classes).

For Dict an object of class Dict.

Arguments

.x

any R object.

...

additional arguments to be passed to or from methods.

old

old element to be found and replaced.

new

the new element replacing the old one.

add

logical if FALSE (default) and element was not found, an error is given. In contrast, if set to TRUE the new element is added regardless of whether it is used as a replacement for an existing element or just added as a new element.

Details

replace uses copy semantics while ref_replace works by reference.

Examples

Run this code

co = container("x", 9)
replace(co, 9, 0)
replace(co, "x", 0)
try({
replace(co, "z", 0)              # old element ("z") is not in Container
})
replace(co, "z", 0, add = TRUE)  # just add the zero without replacement


d = dict(a = 1, b = "z")
replace(d, 1, 1:5)
replace(d, "z", "a")

try({
replace(d, "a", 2)              # old element ("a") is not in Dict
})

Run the code above in your browser using DataLab