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@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.