我有2个数据帧,第一列相同。
df1 = data.frame(Probe = c(1:6), Date = c(rep("2016", 2), rep("2017", 2), rep("2018", 2)), Depth = c(rep("30", 3), rep("60", 3)), Insects = sample(1:10, 6, replace=FALSE), Komments = c(NA,NA, "Error",NA,NA,NA))
df2 = data.frame(Probe = c(1:6), Date = c(rep("2016", 2), rep("2017", 2), rep("2018", 2)), Depth = c(rep("30", 3), rep("60", 3)), Insects = sample(1:10, 6, replace=FALSE), Comments = c(NA,NA,"Error",NA,NA,"Error"))
我已经找到dplyr的merge和left_join,但是如果前三列匹配,我找不到找到将df2中的昆虫数量添加到df1中的方法。 另外,我想添加评论。如果在两个数据框中都有注释,我想在第3行中生成一个“错误,错误”。
有人可以帮助我吗?
答案 0 :(得分:1)
library(dplyr)
df1 %>% left_join(df2,by=c('Probe','Date','Depth')) %>%
mutate(Comment=if_else(!is.na(Komments) & !is.na(Comments),paste0(Komments,',',Comments),NA_character_))