【问题标题】:How to add values of colums in 2 data frames if first rows are identical?如果第一行相同,如何在 2 个数据框中添加列的值?
【发布时间】:2019-01-05 19:28:31
【问题描述】:

我有 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,但是如果前 3 列匹配,我找不到将 df2 中的昆虫数量添加到 df1 的方法。 此外,我想添加 cmets。如果两个数据帧中都有 cmets,我想在第 3 行生成一个“错误,错误”。

谁能帮帮我?

【问题讨论】:

    标签: r


    【解决方案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_))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 2019-05-20
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2022-07-07
      相关资源
      最近更新 更多