How to aggregate matrix columns by row names in R?


To aggregate matrix columns by row names, we can use colSums with sapply and transpose the output. For example, if we have a matrix called M then the aggregate matrix columns by row names can be done using t(sapply(by(M,rownames(M),colSums),identity)).

Example1

Consider the below matrix −

Live Demo

> M1<-matrix(rpois(40,2),ncol=2)
> rownames(M1)<-sample(c("A","B","C","D"),20,replace=TRUE)
> M1

Output

  [,1] [,2]
B    4    6
D    2    1
B    1    5
C    0    0
A    2    3
B    1    0
B    5    3
D    1    3
C    0    1
C    0    2
D    1    1
B    7    2
C    2    3
C    2    3
C    2    2
C    1    2
B    1    1
C    5    3
D    2    2
D    5    2

Finding the aggregate of M1 by row names −

> t(sapply(by(M1,rownames(M1),colSums),identity))

Output

  V1 V2
A  2  3
B 19 17
C 12 16
D 11  9

Example2

Live Demo

> M2<-matrix(rpois(40,10),ncol=2)
> rownames(M2)<-sample(c("S1","S2","S3"),20,replace=TRUE)
> M2

Output

   [,1] [,2]
S1    6   10
S3    7   11
S3   13    6
S1    9    9
S2   11    9
S3    6    8
S1    4    5
S3    8   12
S2   14    8
S3   11    7
S1   15   12
S3    8   13
S3    9   10
S1   10    8
S2   14   18
S1   13   10
S1   10    4
S3   12    7
S2    5    9
S3   13    8

Finding the aggregate of M2 by row names −

> t(sapply(by(M2,rownames(M2),colSums),identity))

Output

   V1 V2
S1 67 58
S2 44 44
S3 87 82

Updated on: 06-Mar-2021

835 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements