我有以下数据:
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
包含变量var1
和dt_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)
但它不起作用。有什么帮助吗?
答案 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