Elizabeth
Elizabeth

Reputation: 6561

merge by row.name and column

This should be simple an I am probably just being silly but... I need to merge two data frames by the row names of df1 and a column in df2 i.e.

df1<-data.frame(x=1:3,y=4:6) 
rownames(df1)<-c("a","b","c")
df1
  x y
a 1 4
b 2 5
c 3 6

df2<-data.frame(site=c("a","b"),p=5:6,q=10:11)
df2
  site p  q
     a 5 10
     b 6 11

The merge should produce:

df3<-data.frame(site=c("a","b"),p=5:6,q=10:11,x=1:2,y=4:5)
df3
  site p  q x y
     a 5 10 1 4
     b 6 11 2 5

I have tried

merge(df1,df2,by.x=row.names(df1),by.y=df2$site) 

but get the error

Error in fix.by(by.x, x) : 'by' must specify uniquely valid column(s)

What am I doing wrong?

Upvotes: 11

Views: 26210

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

Here is one option:

merge(df1, df2, by.x = "row.names", by.y = "site")
  Row.names x y p  q
1         a 1 4 5 10
2         b 2 5 6 11

Upvotes: 13

seancarmody
seancarmody

Reputation: 6290

The 'by' arguments need to be column names. Something like this would work

merge(cbind(df1, row=row.names(df1)), df2, by.x="row", by.y="site")

Upvotes: 5

Related Questions