简体   繁体   中英

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 ie

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?

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM