[R] combining dataframes into single df with all columns

Rui Barradas ruipbarradas at sapo.pt
Thu Feb 7 20:16:11 CET 2013


Hello,

The following function will give what you seem to want.


fun <- function(x, y){
	df3 <- x
	df3 <- cbind(df3, df2[setdiff(names(y), names(x))])
	df3[order(names(df3))]
}

fun(df1, df3)



Hope this helps,

Rui Barradas

Em 07-02-2013 18:36, Anika Masters escreveu:
> #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 ) ) )
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list