[R] merging or joining 2 dataframes: merge, rbind.fill, etc.?

Anika Masters anika.masters at gmail.com
Tue Feb 26 19:55:32 CET 2013


#I want to "merge" or "join" 2 dataframes (df1 & df2) into a 3rd
(mydf).  I want the 3rd dataframe to contain 1 row for each row in df1
& df2, and all the columns in both df1 & df2. The solution should
"work" even if the 2 dataframes are identical, and even if the 2
dataframes do not have the same column names.  The rbind.fill function
seems to work.  For learning purposes, are there other "good" ways to
solve this problem, using merge or other functions other than
rbind.fill?

#e.g. These 3 examples all seem to "work" correctly and as I hoped:

df1 <- data.frame(matrix(data=c(7, 99, 12) ,  nrow=1 ,  dimnames =
list( NULL ,  c('a' , 'b' , 'd') ) ) )
df2 <- data.frame(matrix(data=c(88, 34, 12, 44, 56) ,  nrow=1 ,
dimnames = list( NULL ,  c('d' , 'b' , 'x' ,  'y', 'c') ) ) )
mydf <- merge(df2, df1, all.y=T, all.x=T)
mydf

#e.g. this works:
library(reshape)
mydf <- rbind.fill(df1, df2)
mydf

#This works:
library(reshape)
mydf <- rbind.fill(df1, df2)
mydf

#But this does not (the 2 dataframes are identical)
df1 <- data.frame(matrix(data=c(7, 99, 12) ,  nrow=1 ,  dimnames =
list( NULL ,  c('a' , 'b' , 'd') ) ) )
df2 <- df1
mydf <- merge(df2, df1, all.y=T, all.x=T)
mydf

#Any way to get "mere" to work for this final example? Any other good solutions?



More information about the R-help mailing list