【问题标题】:Appending list items附加列表项
【发布时间】:2016-06-17 11:57:38
【问题描述】:

我有一些长度的列表(比如说 1000)。列表的每个元素都是长度 = 2 的另一个列表。新列表的每个元素都是一个 data.table。每个列表的第二个元素可能是一个空的 data.table。

我需要 rbind() 位于列表第一个位置的所有 data.frames。我目前正在做以下事情:

DT1 = data.table()
DT2 = data.table()
for (i in 1:length(myList)){
     DT1 = rbind(DT1, myList[[i]][[1]]
     DT2 = rbind(DT2, myList[[i]][[2]]
}

这行得通,但是太慢了。有没有办法避免for循环?

提前谢谢你!

【问题讨论】:

  • 即使您可以避免 for 循环,它也会很慢,因为您使用 rbind 广泛地增长数据帧。
  • rbindlist(lapply(mylist, `[[`, 1L))?
  • 非常感谢,这比其他所有建议都快!请发布它,以便我可以“接受”您的回答。

标签: r data.table rbind


【解决方案1】:

数据表有专门的快速功能:rbindlist 参考:http://www.inside-r.org/packages/cran/data.table/docs/rbindlist

已编辑:

这是一个代码示例

 library(data.table)            
srcList=list(list(DT1=data.table(X=0),DT2=NULL),list(DT1=data.table(X=2),data.table(Y=3)))
# first have a list for all DT1s
DT1.list= lapply(srcList, FUN=function(el){el$DT1})
rbindlist(DT1.list)

   X
1: 0
2: 2

【讨论】:

  • 感谢您这么快回复。我看到了这个函数,但我不太明白如何将它应用于绑定到列表列表
  • 结合一种方式来选择合适的DT,例如用lapply(myLisr, FUN=function(el) el[[1]])创建DT1
  • 完成。如果我们已经定义了玩具数据,这会更容易。
【解决方案2】:

这样做:

do.call("rbind", lapply(df.list, "[[", 1)) # for first list element

  # x  y
# 1 1 10
# 2 2 20
# 3 3 30
# 4 4 40
# 5 5 50
# 6 6 60

do.call("rbind", lapply(df.list, "[[", 2)) # for second list element

  # x  y
# 1 1 30
# 2 2 40
# 3 3 50
# 4 4 70
# 5 5 80
# 6 6 90

数据

df.list=list(list(structure(list(x = 1:3, y = c(10, 20, 30)), .Names = c("x", 
"y"), row.names = c(NA, -3L), class = "data.frame"), structure(list(
    x = 1:3, y = c(30, 40, 50)), .Names = c("x", "y"), row.names = c(NA, 
-3L), class = "data.frame")), list(structure(list(x = 4:6, y = c(40, 
50, 60)), .Names = c("x", "y"), row.names = c(NA, -3L), class = "data.frame"), 
    structure(list(x = 4:6, y = c(70, 80, 90)), .Names = c("x", 
    "y"), row.names = c(NA, -3L), class = "data.frame")))

# df.list

# [[1]]
# [[1]][[1]]
  # x  y
# 1 1 10
# 2 2 20
# 3 3 30

# [[1]][[2]]
  # x  y
# 1 1 30
# 2 2 40
# 3 3 50


# [[2]]
# [[2]][[1]]
  # x  y
# 1 4 40
# 2 5 50
# 3 6 60

# [[2]][[2]]
  # x  y
# 1 4 70
# 2 5 80
# 3 6 90

【讨论】:

  • 感谢您发布如此翔实和详细的回复!
  • @GerasimosPanagiotakopoulos 你可以投票而不是感谢! :-)
  • 我做了,但由于声誉低,它还不能显示。
猜你喜欢
  • 1970-01-01
  • 2018-01-24
  • 2011-12-09
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 2020-07-07
  • 2011-10-12
  • 2012-11-01
相关资源
最近更新 更多