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

查看:99
本文介绍了在多列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天全站免登陆