Learn R Programming

container (version 1.1.0)

OpsReplace: Replace Parts of a Container

Description

Replace parts of a Container object similar to R's base list replacement operators, with extended indexing options matching extraction.

Usage

# S3 method for Container
[(x, i, ...) <- value

# S3 method for Container [[(x, i) <- value

# S3 method for Container $(x, name) <- value

Arguments

x

Container object in which to replace elements.

i, ...

Indices specifying elements to replace. Indices may be numeric, character, logical, NULL, or empty. Logical vectors are recycled as needed. Negative integers and negative character tokens select the complement (i.e., drop-by-position or drop-by-name) and the resulting kept positions are replaced. Range expressions such as a:b, 1:c, or d:2 are supported for convenience and are resolved in the calling environment (non-standard evaluation). Comma-separated indices and list(...) are accepted and behave like a single combined index.

value

the replacing value of ANY type

name

character string (possibly backtick quoted)

Details

  • [<- replaces multiple values. Indices can be numeric, character, logical, or a list combining them, including NSE ranges as in extraction. Unknown character indices add new elements (equivalent to .add = TRUE). Numeric indices must be within bounds and will error if out of range. Using an empty index x[] <- v targets all positions. Zero-length selections (e.g., integer(0)) perform no replacement.

  • [[<- replaces a single value at a given numeric or character index. Instead of an index, it is also possible to replace certain elements by passing the element in curly braces (see Examples), that is, the object is searched for the element and then the element is replaced by the value.

  • $<- replaces a single element at a given name.

Examples

Run this code
co = container(a = 1, b = "bar")
(co[1:2] <- 1:2)

try({
co[3] <- 3 # index out of range
})
(co[list(1, "b")] <- 3:4)   # mixed numeric/character index

co = container(a = 1, b = 2)
co[[1]] <- 9
co[["b"]] <- 8
co[["x"]] <- 7
co$z <- 99
print(co)

# Replace 8 by 0
co[[{8}]] <- 0
print(co)


co = container(a = 1, b = "bar")
co$f <- 3
co$b <- 2
co

Run the code above in your browser using DataLab