【问题标题】:Merge, and its result in R合并,其结果在 R
【发布时间】:2022-01-22 14:36:11
【问题描述】:

我想在 R 中合并数据集,但我想知道在合并过程之后哪一行成功合并。 在Stata中,_merge列在合并过程后自动生成,该列有3个值,分别为master only(1), using only(2), and matched(3)You can see the output screenshot here.

我觉得R也有这个功能,但是很难搜索。

【问题讨论】:

    标签: r merge stata


    【解决方案1】:

    我会添加允许识别来源的列

    df1 <- data.frame(x=c("a","b","c"), y=c(1,2,3))
    df2 <- data.frame(x=c("a","b","d"), z=c(1,2,NA))
    
    # solution:
    df1$in1 <- TRUE
    df2$in2 <- TRUE
    merge(df1, df2, all=TRUE)
    

    添加标签作为示例

    df3$source <- ifelse(df3$in1 & is.na(df3$in2), "master only", 
                         ifelse(df3$in2 & is.na(df3$in1), "using only", "matched"))
    df3$in1 <- NULL
    df3$in2 <- NULL
    

    【讨论】:

    • 谢谢。另外,我想添加一些代码:df %&gt;% mutate(merge=ifelse(in1 == TRUE &amp; in2 == NA, "master only", ifelse(in1 == NA &amp; in2 == TRUE, "using only", "matched")))) 但它不能顺利运行。
    • 使用 is.na() 而不是 ... == NA - 查看更新后的答案
    • 非常感谢...!!! :D 你的答案对我来说是完美的。
    猜你喜欢
    • 2014-11-14
    • 2023-04-10
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多