gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:43:35 24 4
gpt4 key购买 nike

我有以下数据:

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看起来像这样:
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)

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

最佳答案

您可以使用 lapply并在函数内部合并:

lapply(lista, function(x) if (!is.null(x$var1)) {

#the function checks if there is a var1 column
#and if there is, it gets merged to the x data.table
return(merge(dt_main, x, by = 'var1', all.x = TRUE))

} else {

#otherwise it just returns the data.table
return(x)

})

# [[1]]
# var1 var4 var2
# 1: wk1 100 1
# 2: wk1 100 2
# 3: wk2 200 3
#
# [[2]]
# var3 var2
# 1: a 1
# 2: b 2
# 3: c 3

关于r - 如何在条件下将列表的所有元素与另一个数据表合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com