rbindlist data.tables 个不同的维度

rbindlist data.tables different dimensions

我用不同的输出多次执行一个函数,如示例所示。

require(data.table)
myfunction<-function(x){
DT1<-data.table(a=c(1,2,3),b=c("a","b","c"))
DT2<-data.table(d=c(4,5,6), e=c("d","e","f"))
return(list(DT1=DT1, DT2=DT2))
}
result<-lapply(1:2, myfunction)

我想绑定结果。所需的输出将与我显示的一样。我的真实示例使用了数百个表。

l1<-rbindlist(list(result[[1]]$DT1, result[[2]]$DT1), idcol = TRUE)
l2<-rbindlist(list(result[[1]]$DT2, result[[2]]$DT2), idcol = TRUE)
DESIRED_OUTPUT<-list(l1, l2)

我使用了这个选项但是没有用: rbindlist data.tables wtih different number of columns

=========================================== =========================

更新

当列表的元素数量不等于 2 时,@nicola 提出的选项不起作用。对于第一个示例(DT1 和 DT2)。作为解决方案,我创建了一个变量 "l" 来计算函数列表中的元素数量。

带有解决方案的新示例。

require(data.table)
myfunction<-function(x){
DT1<-data.table(a=c(1,2,3),b=c("a","b","c"))
DT2<-data.table(d=c(4,5), e=c("d","e"))
DT3<-data.table(f=c(7,8,NA,9), g=c("g","h","i","j"))
return(list(DT1=DT1, DT2=DT2, DT3=DT3))
}
result<-lapply(1:5, myfunction)

l<-unique(sapply(result, length))
apply(matrix(unlist(result,recursive=FALSE),nrow=l),1,rbindlist,idcol=TRUE)

尝试匹配列表组件的名称:

Map(
  function(LL,n) rbindlist(unname(LL[names(l) %in% n]), idcol=TRUE),
  list(unlist(result, recursive=FALSE)),
  unique(names(l))
)

#[[1]]
#   .id a b
#1:   1 1 a
#2:   1 2 b
#3:   1 3 c
#4:   2 1 a
#5:   2 2 b
#6:   2 3 c
#
#[[2]]
#   .id d e
#1:   1 4 d
#2:   1 5 e
#3:   1 6 f
#4:   2 4 d
#5:   2 5 e
#6:   2 6 f

这里有一个选项:

do.call(function(...) Map(function(...) rbind(..., idcol = T), ...), result)
#$DT1
#   .id a b
#1:   1 1 a
#2:   1 2 b
#3:   1 3 c
#4:   2 1 a
#5:   2 2 b
#6:   2 3 c
#
#$DT2
#   .id d e
#1:   1 4 d
#2:   1 5 e
#3:   1 6 f
#4:   2 4 d
#5:   2 5 e
#6:   2 6 f

这是另一个:

lapply(purrr::transpose(result), rbindlist, idcol = T)