合并,其结果在 R
Posted
技术标签:
【中文标题】合并,其结果在 R【英文标题】:Merge, and its result in 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也有这个功能,但是很难搜索。
【问题讨论】:
【参考方案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 %>% mutate(merge=ifelse(in1 == TRUE & in2 == NA, "master only", ifelse(in1 == NA & in2 == TRUE, "using only", "matched"))))
但它不能顺利运行。
使用 is.na()
而不是 ... == NA
- 查看更新后的答案
非常感谢...!!! :D 你的答案对我来说是完美的。以上是关于合并,其结果在 R的主要内容,如果未能解决你的问题,请参考以下文章
R 中merge()函数匹配数据或根据一列或多列来合并两个数据框