如何选择第二个data.table中的所有data.table列

时间:2014-09-23 14:09:00

标签: r data.table

我有几个data.tables具有相同的列,并且有一些额外的列。我想把它们全部绑定,但仅限于公共列

使用data.frames我可以做到

 rbind(df1[,names(df2)],df2,df3,...)

我当然可以用

形式写下所有列名
  list(col1,col2,col3,col4) 

但如果有1,000个变量

,这不是很优雅,也不可行

我相信有一种方法,我没有到达那里 - 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

可能你可以试试:

DT1 <- data.table(Col1=1:5, Col2=6:10, Col3=2:6)
DT2 <- data.table(Col1=1:4, Col3=2:5)
DT3 <- data.table(Col1=1:7, Col3=1:7)
lst1 <- mget(ls(pattern="DT\\d+"))

ColstoRbind <- Reduce(`intersect`,lapply(lst1, colnames))
res <- rbindlist(lapply(lst1, function(x) x[,ColstoRbind,with=FALSE]))
res
#    Col1 Col3
# 1:    1    2
# 2:    2    3
# 3:    3    4
# 4:    4    5
# 5:    5    6
# 6:    1    2
# 7:    2    3
# 8:    3    4
# 9:    4    5
#10:    1    1
#11:    2    2
#12:    3    3
#13:    4    4
#14:    5    5
#15:    6    6
#16:    7    7

更新

正如@Arun在评论中建议的那样,这可能会更好

rbindlist(lapply(lst1, function(x) {
          if(length(setdiff(colnames(x), ColstoRbind))>0) {  
               x[,ColstoRbind, with=FALSE]
               }
              else x}))
相关问题