假设我有这个数据框列表:
library(tidyverse)
df_list <- list(data.frame(cheese = c("ex","ok","bd"),
cheese_val = c(3:1),
stringsAsFactors = F),
data.frame(egg = c("great","good","bad", "eww"),
egg_val = c(4:1),
stringsAsFactors = F),
data.frame(milk = c("good","bad"),
milk_val = c(2:1),
stringsAsFactors = F))
我有这个核心数据集:
core_dat <- data.frame(cheese = c("ex","ok","ok", "bd", "ok"),
egg = c("great", "bad", "bad", "eww", "great"),
milk = c("good", "good", "good", "bad", "good"),
stringsAsFactors = F)
我想core_dat
单独加入df_list
的每个元素。
然后我尝试了这个:
for(i in 1:length(df_list)) {
gg<-core_dat %>%
left_join(df_list[[i]], by = names(df_list[[i]][1]), copy = T)
}
已运行但仅将联接应用于milk
列,因此core_dat
中唯一的其他列为milk_val
,但我希望看到cheese_val
和{{ 1}}。
我怀疑这里有比for循环更合适的选项,我正在寻找建议。请注意,我的实际数据集比这个小例子有更多的df。
我不应该期望结果数据框(在本例中为egg_val
)总共包含6列(3个标准名称+ 3,带有“val”后缀),使得它看起来像这样的打印版本:
gg
我在这里看到了许多“多个连接”的答案,但没有一个与我在这里想要完成的事情完全一致(不同的键列,不同的数据长度)。
答案 0 :(得分:2)
您可以使用map
获取已加入数据框的列表,然后使用reduce
将它们全部加入。
map(df_list, right_join, rownames_to_column(core_dat)) %>%
reduce(full_join)
# Joining, by = "cheese"
# Joining, by = "egg"
# Joining, by = "milk"
# Joining, by = c("cheese", "rowname", "egg", "milk")
# Joining, by = c("cheese", "rowname", "egg", "milk")
# cheese cheese_val rowname egg milk egg_val milk_val
# 1 ex 3 1 great good 4 2
# 2 ok 2 2 bad good 2 2
# 3 ok 2 3 bad good 2 2
# 4 bd 1 4 eww bad 1 1
# 5 ok 2 5 great good 4 2
答案 1 :(得分:2)
这应该给出所需的输出:
Reduce(merge,c(df_list,list(core_dat)))
cheese egg milk cheese_val egg_val milk_val
1 bd eww bad 1 1 1
2 ex great good 3 4 2
3 ok bad good 2 2 2
4 ok bad good 2 2 2
5 ok great good 2 4 2