Learn R Programming

container (version 1.0.5)

replace_at: Replace Values at Indices Safely

Description

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

Usage

replace_at(.x, ...)

ref_replace_at(.x, ...)

# S3 method for Container replace_at(.x, ..., .add = FALSE)

# S3 method for Container ref_replace_at(.x, ..., .add = FALSE)

# S3 method for dict.table replace_at(.x, ..., .add = FALSE)

# S3 method for dict.table ref_replace_at(.x, ..., .add = FALSE)

Value

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

For dict.table an object of class dict.table.

Arguments

.x

any R object.

...

either name = value pairs or two vectors/lists with names/values to be replaced.

.add

logical if FALSE (default) and index is invalid, an error is given. If set to TRUE the new element is added at the given index regardless whether the index existed or not. Indices can consist of numbers or names or both, except when adding values at new indices, which is only allowed for names.

Details

replace_at uses copy semantics while ref_replace_at works by reference.

Examples

Run this code

co = container(a = 0, b = "z")
replace_at(co, a = 1, b = 2)
replace_at(co, 1:2, 1:2)                 # same
replace_at(co, c("a", "b"), list(1, 2))  # same

try({
replace_at(co, x = 1)                    # names(s) not found: 'x'
})
replace_at(co, x = 1, .add = TRUE)       # ok (adds x = 1)


dit = dict.table(a = 1:3, b = 4:6)
replace_at(dit, a = 3:1)
replace_at(dit, 1, 3:1)                  # same
replace_at(dit, "a", 3:1)                # same
replace_at(dit, a = 3:1, b = 6:4)
replace_at(dit, 1:2, list(3:1, 6:4))     # same

try({
replace_at(dit, x = 1)                   # column(s) not found: 'x'
})
replace_at(dit, x = 1, .add = TRUE)      # ok (adds column)

Run the code above in your browser using DataLab