r中数据帧之间的两个匹配 [英] Two by two matching between dataframes in r

查看:287
本文介绍了r中数据帧之间的两个匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过匹配每个数据帧的两个站点列来生成第三个数据帧(df3)来组合两个数据帧(df1和df2)。

I need to combine two data frames (df1 and df2) by matching up two site columns of each data frame to produce a third data frame (df3).

df1 = data.frame(Site.1=c("A","A","B"),
                 Site.2=c("B","C","C"),
                 Score1=c(60,70,80))
df1

 Site.1 Site.2 Score1
1      A      B     60
2      A      C     70
3      B      C     80

df2 = data.frame(Site.1=c("B","A","A"),
                 Site.2=c("C","B","C"),
                 Score2=c(10,20,30))
df2

  Site.1 Site.2 Score2
1      B      C     10
2      A      B     20
3      A      C     30

df3 = data.frame(Site.1=c("A","A","B"),
                 Site.2=c("B","C","C"),
                 Score1=c(60,70,80),
                 Score2=c(20,30,10))
df3

  Site.1 Site.2 Score1 Score2
1      A      B     60     20
2      A      C     70     30
3      B      C     80     10


推荐答案

您想要合并函数。由于您要匹配的列名称已经具有相同的名称,因此您甚至不需要特别处理。如果不是这样,您可以查看合并的 by.x by.y 参数

You want the merge function. Since your column names that you want to match on already have the same name you don't even need to do anything special. If that wasn't the case you would want to look into the by.x and by.y parameters that merge takes.

df1 = data.frame(Site.1=c("A","A","B"),Site.2=c("B","C","C"),Score1=c(60,70,80))
df2 = data.frame(Site.1=c("B","A","A"),Site.2=c("C","B","C"), Score2=c(10,20,30))
df3 = data.frame(Site.1=c("A","A","B"),Site.2=c("B","C","C"), Score1=c(60,70,80),Score2=c(20,30,10))
df3

# Merge gives you what you want
merge(df1, df2)

这篇关于r中数据帧之间的两个匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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