Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

r - Create a variable length `alist()`

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

OK, I'll bite. I would probably use list(bquote()) to construct a one element list containing the empty symbol, and rep that out to the desired length.

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

As a bonus, here is a collection of 5 ways to create/access the empty symbol that is needed as the content of each list element:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...