如何在条件下将列表的所有元素与另一个数据表合并

时间:2017-11-29 09:44:12

标签: r list merge data.table

我有以下数据:

library(data.table)

dt1 <- data.table(var1 = c("wk1","wk1","wk2"),
                  var2 = c(1,2,3))

dt2 <- data.table(var3 = c("a","b","c"),
                  var2 = c(1,2,3))

lista <- list(dt1,dt2)

dt_main <- data.table(var1 = c("wk1","wk2"),
                      var4 = c(100,200))

我想merge lista包含变量var1dt_main data.table的所有元素,所以最后我希望lista 1}}看起来像这样:

dt1 <- data.table(var1 = c("wk1","wk1","wk2"),
                  var2 = c(1,2,3),
                  var4 = c(100,100,200))

dt2 <- data.table(var3 = c("a","b","c"),
                  var2 = c(1,2,3))

lista <- list(dt1,dt2)

我试过

mapply(function(X,Y){
  if("var1"%in%names(X)){
    X <- merge(X,Y,by="var1")
  }
},X=lista,Y=dt_main)

但它不起作用。有什么帮助吗?

1 个答案:

答案 0 :(得分:4)

执行此操作的方式略有不同:

lapply(lista, function(x) if ('var1' %in% names(x))
  x[dt_main, on = 'var1', var4 := var4][]
  else x
  )

给出:

[[1]]
   var1 var2 var4
1:  wk1    1  100
2:  wk1    2  100
3:  wk2    3  200

[[2]]
   var3 var2
1:    a    1
2:    b    2
3:    c    3