首页 > 解决方案 > 大规模申报清单的更清洁方法?

问题描述

我有一个迭代过程,涉及将修改/使用的数据附加到列表的子列表中。声明一堆列表(例如testList <- list()x 12)感觉很混乱,所以在循环中我可以直接跳到下面的代码:

testList <- list()
otherTestList <- list()
anotherTestList <- list()

for(i in 1:10){
  testList[[i]] <- testData
  otherTestList[[i]] <- otherTestData
  anotherTestList[[i]] <- anotherTestData
}

上面的代码需要在代码开头声明 3 个列表,这不是什么大问题,但是我有大约 12 个列表,所以它们的大量声明使代码非常难看。我想知道这个问题是否有解决方案?我考虑过的事情是使用 lapply 在一行中创建列表,但这似乎不是一个选项,因为需要在将对象用作列表之前将它们声明为某种类型。

标签: rlist

解决方案


您可以使用assign(). 假设您有列表的名称或想要迭代地设置它们:

for (i in 1:5){
  assign(paste0("x",i),list())
}

如果你有名字:

listnames = c("testList", "otherTestList","anotherTestList", ...)
    for (i in 1:5){
      assign(listnames[i],list())
    }

这将为您提供 5 个名为x1, x2or testList, otherTestList... 的变量,每个变量都包含一个空列表。


推荐阅读