unloadNamespace("dplyr") require(container) has = container::has has_name = container::has_name knitr::opts_chunk$set( comment = "#", prompt = F, tidy = FALSE, cache = FALSE, collapse = T ) old <- options(width = 100L)
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
.
library(container) co <- cont(a = 1, b = 1:10) # same as co = container(a = 1, b = 1:10)
The container print method is designed to be very compact.
print(co)
For more verbose output, either convert to a base list
...
as.list(co)
or use str
.
str(co)
Both length
and names
work as usual.
length(co) names(co) names(co)[1] <- "A" co
A container can also be constructed from a list.
l <- list(x = (1:2)^1, y = (1:2)^2) co2 <- as.container(l) co2
Elements can be added by concatenation,
c(co, c = 3, d = 4) c(co, co2)
or name,
co[["c"]] <- 3 co
and containers can be nested.
co[["co2"]] <- co2 co
In contrast to base R list
, elements cannot be added via positional index
if it exceeds the container's length.
co[[5]] <- 5
Single or multiple value replacement works as usual.
co[[3]] <- 0 co[1:2] <- 0 co
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
Another option is to replace by value.
co[[{"three"}]] <- 3 co
This works for any data type.
co[[{co2}]] <- 3 co
The following standard access operators can be applied.
co[["A"]] co[[1]] co[1:3]
At this point, neither the $
operator nor negative indices^[Negative indexing support
is planned for the next version.] are supported.
They just give empty results.
co$A co[-1]
For now, a workaround for negative indexing is to temporarily convert to a list.
tmp <- as.list(co) as.container(tmp[-1])
As another option, you can pass any number of indices, possibly mixed as numeric and character.
co[1, 3, "b"] co[2:1, "A"]
Invalid indices don't produce NULL
s but are just ignored.
co[1:33] co[3:33] co[10:20]
Count the number of elements.
count(co, 1) count(co, 3)
This vignette showcases how {container} enhances interactive R workflows by combining the familiarity of base R list operations with additional features:
Next, see vignette Use container for code development.
options(old)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.