[R] combining dataframes into single df with all columns

Anika Masters anika.masters at gmail.com
Thu Feb 7 19:36:32 CET 2013


#I have 2 dataframes df1 & df2.  Each has a subset of all possible column names.
#How do I combine the 2 tables so that they contain all column names?

data1 <- c('2','3', '6', '8' , '9')
data2 <- c('1', '2', '3', '6')
df1 <- data.frame(matrix(data=NA, nrow=1, ncol=length(data1),
dimnames=list(NULL, paste('col', data1, sep='') ) ) )
df2 <- data.frame(matrix(data=data2, nrow=1, ncol=length(data2),
dimnames=list(NULL, paste('col', data2, sep='') ) ) )

e.g.
data1 <- c('2','3', '6', '8' , '9')
data2 <- c('1', '2', '3', '6')
df1 <- data.frame(matrix(data=NA, nrow=1, ncol=length(data1),
dimnames=list(NULL, paste('col', data1, sep='') ) ) )
df2 <- data.frame(matrix(data=data2, nrow=1, ncol=length(data2),
dimnames=list(NULL, paste('col', data2, sep='') ) ) )

#I want:
names3 <- sort( unique(c(names(df1), names(df2) ) ) )
df3 <- data.frame(matrix(data=c('1','2','3','6','8','9'), nrow=1,
ncol=length(names3), dimnames=list(NULL, names3 ) ) )



More information about the R-help mailing list