我想使用第三个data.frame matches
合并两个data.frame,它提供了如何合并前两个数据的键(id
和number
是匹配的键。Class
应该始终匹配,并且用作附加检查)。
df2
应该合并到df1
中,以替换具有相同名称的列,并将变量df2
中的变量插入到df1
的相应行中(在此示例中,这些行将被计分,但在我的实际示例中,大约20列以上的列应在30列左右的列中进行替换(其余10列将保持不变)。我希望这一点很清楚,并在此先感谢非常感谢,以帮助您高效地进行操作。
由于我想将所有记录保留在left_join
中,因此它必须为df1
。 dplyr
是首选项!
df1 <- data.frame(1:10,
c("a","b","a","b","c","c","b","a","b","c"),
seq(20,38,2),
dnorm(10,5,2),
rnorm(10,78,5))
colnames(df1) <- c("id","class","score","misc","hc")
df2 <- data.frame(11:19,
c("g","d","a","e","c","d","f","a","b"),
seq(40,48,1),
dnorm(9,6,1),
rnorm(9,45,3))
colnames(df2) <- c("number","class","score","other","md")
matches <- data.frame(c("b","a","c","a"),
c(4,1,5,8),
c(19,18,15,13))
colnames(matches) <- c("class","id","number")
library(dplyr)
预期输出:
id class misc hc number score other md
1 a 0.00876415 70.85210 18 47 0.004431848 40.99189
2 b 0.00876415 81.27802 22 22 NA NA
3 a 0.00876415 69.19300 24 24 NA NA
4 b 0.00876415 75.86247 19 48 0.004431848 44.78242
5 c 0.00876415 69.18268 15 44 0.004431848 42.70708
6 c 0.00876415 80.49475 30 30 NA NA
7 b 0.00876415 76.52195 32 32 NA NA
8 a 0.00876415 73.52712 13 42 0.004431848 45.69842
9 b 0.00876415 81.50631 36 36 NA NA
10 c 0.00876415 80.55145 38 38 NA NA
答案 0 :(得分:2)
使用dplyr
library(dplyr)
df1 %>% left_join(matches,by=c('id','class'),suffix=c('.df1','.df2')) %>%
left_join(df2,by=c('class','number'),suffix=c('.df1','.df2')) %>%
mutate(score=if_else(!is.na(score.df2),score.df2,score.df1)) %>%
select(-score.df1,score.df2)
答案 1 :(得分:1)
只做两个这样的合并:
tmp = merge(df1, matches, all.x = FALSE, all.y = TRUE)
res = merge(tmp, df2, all.x = TRUE, all.y = FALSE)
res