Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

merge - Two by two matching between dataframes in r

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...