Interactive usage
In an interactive R session a container can be used similar to a base
R list
, but also provides some extra features. For easier
typing it’s recommended to use the shorter cont
.
The container print method is designed to be very compact.
print(co)
# [a = 1, b = (1L 2L 3L 4L ...)]
For more verbose output, either convert to a base list
…
as.list(co)
# $a
# [1] 1
#
# $b
# [1] 1 2 3 4 5 6 7 8 9 10
or use str
.
str(co)
# Container of 2
# $ a: num 1
# $ b: int [1:10] 1 2 3 4 5 6 7 8 9 10
Both length
and names
work as usual.
A container can also be constructed from a list.
l <- list(x = (1:2)^1, y = (1:2)^2)
co2 <- as.container(l)
co2
# [x = (1 2), y = (1 4)]
Add
Elements can be added by concatenation,
c(co, c = 3, d = 4)
# [A = 1, b = (1L 2L 3L 4L ...), c = 3, d = 4]
c(co, co2)
# [A = 1, b = (1L 2L 3L 4L ...), x = (1 2), y = (1 4)]
or name,
co[["c"]] <- 3
co
# [A = 1, b = (1L 2L 3L 4L ...), c = 3]
and containers can be nested.
co[["co2"]] <- co2
co
# [A = 1, b = (1L 2L 3L 4L ...), c = 3, co2 = [x = (1 2), y = (1 4)]]
In contrast to base R list
, elements cannot be added via
positional index if it exceeds the container’s length.
co[[5]] <- 5
# Error: index out of range (length = 4): 5
Replace
Single or multiple value replacement works as usual.
co[[3]] <- 0
co[1:2] <- 0
co
# [A = 0, b = 0, c = 0, co2 = [x = (1 2), y = (1 4)]]
In contrast to base list
, containers can take a mix of
numeric and character indices.
co[list("A", 2, "c")] <- list(1, 2, "three")
co
# [A = 1, b = 2, c = "three", co2 = [x = (1 2), y = (1 4)]]
Another option is to replace by value.
co[[{"three"}]] <- 3
co
# [A = 1, b = 2, c = 3, co2 = [x = (1 2), y = (1 4)]]
This works for any data type.
co[[{co2}]] <- 3
co
# [A = 1, b = 2, c = 3, co2 = 3]
Extract
The following standard access operators can be applied.
co[["A"]]
# [1] 1
co[[1]]
# [1] 1
co[1:3]
# [A = 1, b = 2, c = 3]
At this point, neither the $
operator nor negative
indices1
are supported. They just give empty results.
co$A
# NULL
co[-1]
# []
For now, a workaround for negative indexing is to temporarily convert to a list.
tmp <- as.list(co)
as.container(tmp[-1])
# [b = 2, c = 3, co2 = 3]
As another option, you can pass any number of indices, possibly mixed as numeric and character.
co[1, 3, "b"]
# [A = 1, c = 3, b = 2]
co[2:1, "A"]
# [b = 2, A = 1, A = 1]
Invalid indices don’t produce NULL
s but are just
ignored.
co[1:33]
# [A = 1, b = 2, c = 3, co2 = 3]
co[3:33]
# [c = 3, co2 = 3]
co[10:20]
# []
Summary
This vignette showcases how {container} enhances interactive R workflows by combining the familiarity of base R list operations with additional features:
- Compact printing for quick overviews, with options for detailed inspection via as.list() and str().
- Flexible adding and replacing of elements, supporting mixed indices and preventing out-of-bounds additions.
- Intuitive extraction using familiar operators, with safe handling of invalid indices.
Next, see vignette Container operations for robust code.