Combine columns in a matrix with the same column name

I have a matrix with columns that duplicate column names of characters.

set.seed(1) m <- matrix(sample(1:10,12,replace=TRUE), nrow = 3, ncol = 4, byrow = TRUE, dimnames = list(c("s1", "s2", "s3"),c("x", "y","x","y"))) m xyxy s1 3 4 6 10 s2 3 9 10 7 s3 7 1 3 2 

I need to sum all columns with the same column name in only one column i.e.

 m <- matrix(c(9,14,13,16,10,3), nrow = 3, ncol = , byrow = TRUE,dimnames = list(c("s1", "s2", "s3"),c("x", "y"))) xy s1 9 14 s2 13 16 s3 10 3 

I had a game with a simple sum in an aggregate function, but I was out of luck. Any advice? Thanks.

+4
source share
2 answers

Well, this solution will not receive any rewards for code transparency, but I like it:

 nms <- colnames(m) m %*% sapply(unique(nms),"==", nms) # xy # s1 9 14 # s2 13 16 # s3 10 3 

It works by creating a matrix that forms the corresponding linear combinations of columns m . To see how this works, select the second row into two component matrices that are multiplied together with %*% , for example:

  - - - - | 3 4 6 10 | | 1 0 | | 3 9 10 7 | | 0 1 | | 7 1 3 2 | | 1 0 | - - | 0 1 | - - 
+8
source
 nms <- colnames(m) sapply(unique(nms), function(i)rowSums(m[, nms==i])) xy s1 9 14 s2 13 16 s3 10 3 
+6
source

All Articles