[R] Merge matrices with different column names

Rui Barradas ruipbarradas at sapo.pt
Fri Oct 26 11:10:13 CEST 2012


Hello,

If you just want to write the matrices to a csv file instead of 
write.csv you can use write.table with options append=TRUE, sep="," and 
col.names=FALSE.

If you want to merge (rbind) them, you can use code similar to


pattern1 <- "(^var)[[:digit:]]+(.*$)"
pattern2 <- "(^var)_n_(.*$)"

colnames(Matrix1) <- sub(pattern1, "\\1_n_\\2", colnames(Matrix1))
colnames(Matrix2) <- sub(pattern1, "\\1_n_\\2", colnames(Matrix2))

Mat <- rbind(Matrix1, Matrix2)
colnames(Mat) <- sub(pattern2, "\\1_\\2", colnames(Mat))
Mat

Hope this helps,

Rui Barradas
Em 26-10-2012 04:51, Charles Determan Jr escreveu:
> A general question that I have been pursuing for some time but have set
> aside.  When finishing some analysis, I can have multiple matrices that
> have specific column names.  Ideally, I would like to combine these
> separate matrices for a final output as a csv file.
>
> A generic example:
>
> Matrix 1
> var1A          var1B          var1C
> x                      x               x
> x                      x               x
>
> Matrix 2
> var2A          var2B          var2C
> x                      x               x
> x                      x               x
>
> I would like a final exportable matrix or dataframe or whichever format is
> most workable.
>
> Matrix 3
> var1A          var1B          var1C
> x                      x               x
> x                      x               x
>
> var2A          var2B          var2C
> x                      x               x
> x                      x               x
>
> However, no matter which function I try reports an error that the column
> names are not the same.
>
> Any insights would be appreciated.
> Thanks as always,
> Charles
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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