[R] adding matrices with common column names
Dimitris Rizopoulos
d.rizopoulos at erasmusmc.nl
Fri Mar 27 14:47:04 CET 2009
one approach is:
a <- matrix(1:20,ncol=4); colnames(a) <- c("a","b","c","d")
b <- matrix(1:20,ncol=4); colnames(b) <- c("b","c","d", "e")
cc <- matrix(1:10,ncol=2); colnames(cc) <- c("e","f")
f <- function (...) {
mat.lis <- list(...)
unq.cnams <- unique(unlist(lapply(mat.lis, colnames)))
out <- matrix(0, nrow(mat.lis[[1]]), length(unq.cnams),
dimnames = list(NULL, unq.cnams))
for (i in seq_along(mat.lis)) {
mm <- mat.lis[[i]]
out[, colnames(mm)] <- out[, colnames(mm)] + mm
}
out
}
f(a, b)
f(a, cc)
f(a, b, cc)
I hope it helps.
Best,
Dimitris
Murali.MENON at fortisinvestments.com wrote:
> folks,
>
> if i have three matrices, a, b, cc with some colnames in common, and i
> want to create a matrix which consists of the common columns added up,
> and the other columns tacked on, what's a good way to do it? i've got
> the following roundabout code for two matrices, but if the number of
> matrices increases, then i'm a bit stymied.
>
>> a <- matrix(1:20,ncol=4); colnames(a) <- c("a","b","c","d") b <-
>> matrix(1:20,ncol=4); colnames(b) <- c("b","c","d", "e")
>> cbind(a[,!(colnames(a) %in% colnames(b)), drop = FALSE],
> a[,intersect(colnames(a),colnames(b))] +
> b[,intersect(colnames(a),colnames(b)), drop = FALSE],
> b[,!(colnames(b) %in% colnames(a)), drop = FALSE])
>
> a b c d e
> [1,] 1 7 17 27 16
> [2,] 2 9 19 29 17
> [3,] 3 11 21 31 18
> [4,] 4 13 23 33 19
> [5,] 5 15 25 35 20
>
> now, what if i had a matrix cc? i want to perform the above operation on
> all three matrices a, b, cc.
>
>> cc <- matrix(1:10,ncol=2); colnames(cc) <- c("e","f")
>
> i need to end up with:
>
> a b c d e f
> [1,] 1 7 17 27 17 6
> [2,] 2 9 19 29 19 7
> [3,] 3 11 21 31 21 8
> [4,] 4 13 23 33 23 9
> [5,] 5 15 25 35 25 10
>
> and, in general, with multiple matrices with intersecting colnames?
>
> thanks,
>
> murali
>
> ______________________________________________
> 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.
>
--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center
Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
More information about the R-help
mailing list