Anika Masters
2013-Feb-07 18:21 UTC
[R] combining dataframes into single df with all columns
#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 ) ) ) [[alternative HTML version deleted]]
Anika Masters
2013-Feb-07 18:36 UTC
[R] combining dataframes into single df with all columns
#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 ) ) )