Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 附加列表项_R_Data.table_Rbind - Fatal编程技术网

R 附加列表项

R 附加列表项,r,data.table,rbind,R,Data.table,Rbind,我有一个长度一定的列表(比如说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

我有一个长度一定的列表(比如说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循环


提前谢谢你

数据表有一个专用的快速功能:
rbindlist
Cf:

编辑:

下面是一个代码示例

 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
这样做:

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

即使你可以避免for循环,它也会很慢,因为你使用
rbind
大量增加数据帧。
rbindlist(lappy(mylist,`[`,1L))
?非常感谢,这比所有其他建议都快!请发布它,这样我就可以“接受”您的答案。感谢您这么快回复。我看到了函数,但我不太明白如何应用它绑定到列表列表,并结合选择合适的DT的方法,例如使用
lapply(myLisr,FUN=function(el)el[[1]])
创建DT1Done。如果我们已经有了玩具数据的定义,这会更容易。感谢您发布如此详细的回复!@GerasimosPanagiotakopoulos您可以投票赞成而不是表示感谢!:-)我做了,但由于声誉不高,它还不能显示出来。