嵌套列表:如何在输入数据之前定义大小

时间:2013-07-10 09:33:53

标签: r nested-forms

我很擅长在R中使用列表。现在我想创建几个嵌套列表。我已经知道列表应包含的元素数量,现在想在将数据输入到列表之前定义列表的大小。 对于最高级别的列表,其中包含我使用的2个元素

list_example <- vector(mode="list", 2)

现在两个元素中的每一个都应该包含3个元素:再次包含列表的列表等等...总共我有7个级别,即2 * 3 * 3 * 4 * 2 * 3 * 3的树组合。有一种紧凑的方法来定义这种深层嵌套列表结构的大小吗? 非常感谢你提前!!

4 个答案:

答案 0 :(得分:6)

你可以使用递归函数来做到这一点。

rec.list <- function(len){
    if(length(len) == 1){
        vector("list", len)
    } else {
        lapply(1:len[1], function(...) rec.list(len[-1]))
    }
}

l <- rec.list(c(2, 3, 3, 4, 2, 3, 3))

或者使用7-d列表数组?它起初可能看起来很奇怪,但它是一个完全有效的数据结构。

l <- vector("list", 2*3*3*4*2*3*3)
dim(l) <- c(2, 3, 3, 4, 2, 3, 3)
l[[1,1,1,1,1,1,1]] <- "content"

答案 1 :(得分:1)

设置某种参数:

window_front <- 100
horizon <- 10

创建一个空的嵌套列表:

sub_horizon <- vector("list", 27)

for (i in 1:length(sub_horizon)) {
  sub_horizon[[i]] <- vector("list", window_front)
  for (m in 1:length(sub_horizon[[i]])) {
    sub_horizon[[i]][[m]] <- vector("list", horizon)
  }
}

答案 2 :(得分:0)

你的方法对我来说似乎有点复杂。您可能需要考虑使用包含每个元素的案例组合的查找表:

实施例

id <- seq(2*3*3*4*2*3*3) # a vector of identification values

#create a lookup table
lut <- cbind(id=id, expand.grid(lev1=seq(2), lev2=seq(3), lev3=seq(3), lev4=seq(4), lev5=seq(2), lev6=seq(3), lev7=seq(3)))

list.obj <- vector(mode="list", nrow(lut))

#optional addition of names
names(list.obj) <- paste(lut$lev1, lut$lev2, lut$lev3, lut$lev4, lut$lev5, lut$lev6, lut$lev7, sep=".")
head(list.obj)

#fill in list with data
for(i in seq(list.obj)){
    matching <- i #here you can have some sort of case matching for filling in elements of the list
    list.obj[[matching]] <- runif(10)
}
head(list.obj)

我相信这可能会让你的生活变得更容易,因为后来试图挑选你感兴趣的案件的特定元素。

答案 3 :(得分:0)

一种简单的方法来声明,例如,嵌套在5列表中的3列表:

my.list<-lapply(my.list<-vector(mode = 'list',5),function(x) x<-vector(mode='list',3))

summary(my.list)

     Length Class  Mode
[1,] 3      -none- list
[2,] 3      -none- list
[3,] 3      -none- list
[4,] 3      -none- list
[5,] 3      -none- list

如果您想添加另一个嵌套列表,例如2个插槽,只需添加另一个lapply,即:

my.list<-lapply(my.list<-vector(mode = 'list',5),function(x) 
      x<-lapply(x<-vector(mode = 'list',3),function(x) 
      x<-vector(mode='list',2)))

summary(my.list)
     Length Class  Mode
[1,] 3      -none- list
[2,] 3      -none- list
[3,] 3      -none- list
[4,] 3      -none- list
[5,] 3      -none- list

summary(my.list[[1]])
     Length Class  Mode
[1,] 2      -none- list
[2,] 2      -none- list
[3,] 2      -none- list