How to find the row sum for each column by row name in an R matrix?


To find the row sum for each column by row name, we can use rowsum function. For example, if we have a matrix called M then the row sums for each column with row names can be calculated by using the command rowsum(M,row.names(M)).

Example1

Live Demo

> M1<-matrix(rpois(40,5),nrow=20)
> rownames(M1)<-sample(c("Male","Female"),20,replace=TRUE)
> colnames(M1)<-c("V1","V2")
> M1

Output

       V1 V2
Male    3  6
Female  6  5
Female  7  3
Female  2  5
Female  5  3
Female  4  4
Female  1  4
Female  4  4
Female  7  5
Male    2  5
Female  5  5
Male    7  1
Female  5  6
Male    6  5
Female  3  7
Male    5  4
Female  3  6
Male    3  4
Male    4  3
Male    6  2

Finding the row sums with column names of matrix M1 −

> rowsum(M1,row.names(M1))

Output

       V1 V2
Female 52 57
Male   36 30

Example2

Live Demo

> M2<-matrix(rpois(40,10),nrow=20)
> rownames(M2)<-sample(LETTERS[1:4],20,replace=TRUE)
> colnames(M2)<-c("X1","X2")
> M2

Output

   X1 X2
B  6  9
D 12 14
C  8  9
A  9  8
A  6 13
A 10  8
D  7 12
B  9  6
A 11 11
C  6 15
D 12  6
B  5  9
C 12 11
A 12  6
B 10  9
D 15 14
C  8 10
B 11  9
A  8  8
B 19  4

Finding the row sums with column names of matrix M2 −

> rowsum(M2,row.names(M2))

Output

   X1 X2
A 56 54
B 60 46
C 34 45
D 46 46

Example3

Live Demo

> M3<-matrix(sample(0:9,40,replace=TRUE),nrow=20)
> rownames(M3)<-sample(c("Hot","Cold"),20,replace=TRUE)
> colnames(M3)<-c("C1","C2")
> M3

Output

      C1 C2
Cold  1  5
Hot   1  3
Hot   4  5
Cold  0  3
Hot   2  8
Hot   7  6
Hot   5  9
Cold  5  9
Cold  9  9
Cold  8  7
Cold  9  2
Cold  0  6
Cold  0  3
Cold  6  3
Cold  3  8
Cold  6  2
Cold  5  0
Cold  4  9
Cold  9  2
Hot   6  5

Finding the row sums with column names of matrix M3 −

> rowsum(M3,row.names(M3))

Output

     C1 C2
Cold 65 68
Hot  25 36

Updated on: 05-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements