r - Create a variable length `alist()` -


in answer, alist() proposed easy means of creating list empty elements. use case constructing list suitable call [ arranged via do.call(). 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 alist() answer required setting of empty arguments dynamically on basis of object shortdim.

if 1 knew how many dimensions present 1 do

al <- alist( , , ) ## 3 arguments 2-d object al[[1]] <- x shortdim <- 1 al[[shortdim + 1]] <- 1:2 ## elements 1 & 2 of dim shortdim, plus other dims do.call(`[`, al)   > do.call(`[`, al)       [,1] [,2] [1,]    1    4 [2,]    2    5 > x[1:2, ]         ## equivalent      [,1] [,2] [1,]    1    4 [2,]    2    5 

a list of dynamic length can created vector(), eg

ll <- vector(mode = "list", length = length(dim(x)) + 1) 

but alist can't made in way

> vector(mode = "alist", length = length(dim(x)) + 1) error in vector(mode = "alist", length = length(dim(x)) + 1) :    vector: cannot make vector of mode 'alist'. 

is there way create alist of dynamic length can filled in later required?

ok, i'll bite. use list(bquote()) construct 1 element list containing empty symbol, , rep out desired length.

n <- 2 rep(list(bquote()), n) # [[1]] #  #  # [[2]] #  #  

as bonus, here collection of 5 ways create/access empty symbol needed content of each list element:

bquote() #  substitute() #  quote(expr= ) #  formals(function(x) {})$x #  alist(,)[[1]] #  

Comments