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
494 views
in Technique[技术] by (71.8m points)

r - How does one merge dataframes by row name without adding a "Row.names" column?

If I have two data frames, such as:

df1 = data.frame(x=1:3,y=1:3,row.names=c('r1','r2','r3'))
df2 = data.frame(z=5:7,row.names=c('r5','r6','r7'))

(

R> df1
   x y
r1 1 1
r2 2 2
r3 3 3

R> df2
   z
r5 5
r6 6
r7 7

), I'd like to merge them by row names, keeping everything (so an outer join, or all=T). This does it:

merged.df <- merge(df1,df2,all=T,by='row.names')
R> merged.df
  Row.names  x  y  z
1        r1  1  1 NA
2        r2  2  2 NA
3        r3  3  3 NA
4        r5 NA NA  5
5        r6 NA NA  6
6        r7 NA NA  7

but I want the input row names to be the row names in the output dataframe (merged.df).

I can do:

rownames(merged.df) <- merged.df[[1]]
merged.df <- merged.df[-1]

which works, but seems inelegant and hard to remember. Anyone know of a cleaner way?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Not sure if it's any easier to remember, but you can do it all in one step using transform.

transform(merge(df1,df2,by=0,all=TRUE), row.names=Row.names, Row.names=NULL)
#    x  y  z
#r1  1  1 NA
#r2  2  2 NA
#r3  3  3 NA
#r5 NA NA  5
#r6 NA NA  6
#r7 NA NA  7

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

...