Skip to contents

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 class 'Container'
replace(.x, old, new, add = FALSE, ...)

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

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

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

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.

Value

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

For Dict an object of class Dict.

Details

replace uses copy semantics while ref_replace works by reference.

Examples


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


d = dict(a = 1, b = "z")
replace(d, 1, 1:5)
#> {a = (1L 2L 3L 4L ...), b = "z"}
replace(d, "z", "a")
#> {a = 1, b = "a"}

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