合并多列R [英] merging on multiple columns R

查看:30
本文介绍了合并多列R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这不是重复的,我很惊讶,但我在其他任何地方都找不到答案.

I'm surprised if this isn't a duplicate, but I couldn't find the answer anywhere else.

我有两个数据框,data1data2,它们的一列不同,但其余的列是相同的.我想将它们合并到一个唯一的标识列 id.但是,如果 data2 中的 ID 在 data1 中没有匹配项,我希望将 data2 中的条目附加到底部,类似于 plyr::rbind.fill() 而不是将 data2 中所有对应的列重命名为 column1.xcolumn1.y.我意识到这不是最清楚的解释,也许我不应该在星期六工作.这是创建两个数据帧和所需输出的代码:

I have two data frames, data1 and data2, that differ in one column, but the rest of the columns are the same. I would like to merge them on a unique identifying column, id. However, in the event an ID from data2 does not have a match in data1, I want the entry in data2 to be appended at the bottom, similar to plyr::rbind.fill() rather than renaming all the corresponding columns in data2 as column1.x and column1.y. I realize this isn't the clearest explanation, maybe I shouldn't be working on a Saturday. Here is code to create the two dataframes, and the desired output:

spp1 <- c('A','B','C')
spp2 <- c('B','C','D')
trait.1 <- rep(1.1,length(spp1))
trait.2 <- rep(2.0,length(spp2))
id_1 <- c(1,2,3)
id_2 <- c(2,9,7)

data1 <- data.frame(spp1,trait.1,id_1)
data2 <- data.frame(spp2,trait.2,id_2)
colnames(data1) <- c('spp','trait.1','id')
colnames(data2) <- c('spp','trait.2','id')

所需的输出:

  spp trait.1 trait.2 id
1   A     1.1      NA  1
2   B     1.1       2  2
3   C     1.1      NA  3
4   C      NA       2  9
5   D      NA       2  7

推荐答案

试试这个:

library(dplyr)

full_join(data1, data2, by = c("id", "spp"))

输出:

  spp trait.1 id trait.2
1   A     1.1  1      NA
2   B     1.1  2       2
3   C     1.1  3      NA
4   C      NA  9       2
5   D      NA  7       2

或者,merge 也可以:

merge(data1, data2, by = c("id", "spp"), all = TRUE)

这篇关于合并多列R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆