In this Answer, an alist()
is proposed as an easy means of creating a list with empty elements. A use case for this would be constructing a list suitable for a call to [
arranged via do.call()
. For example:
x <- matrix(1:6, ncol = 2)
do.call(`[`, alist(x, , 2)) ## extract column 2 of x
[1] 4 5 6
The particular Question prompting the alist()
Answer required the setting of the empty arguments dynamically on basis of an object shortdim
.
If one knew how many dimensions were present one could do
al <- alist( , , ) ## 3 arguments for a 2-d object
al[[1]] <- x
shortdim <- 1
al[[shortdim + 1]] <- 1:2 ## elements 1 & 2 of dim shortdim, plus all other dims
do.call(`[`, al)
> do.call(`[`, al)
[,1] [,2]
[1,] 1 4
[2,] 2 5
> x[1:2, ] ## equivalent too
[,1] [,2]
[1,] 1 4
[2,] 2 5
A list of dynamic length can be created by vector()
, eg
ll <- vector(mode = "list", length = length(dim(x)) + 1)
But an alist
can't be made in that way
> vector(mode = "alist", length = length(dim(x)) + 1)
Error in vector(mode = "alist", length = length(dim(x)) + 1) :
vector: cannot make a vector of mode 'alist'.
Is there a way to create an alist
of dynamic length that can be filled in later where required?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…