How to find the row total of columns having same name in R matrix?


To find the row total of columns having same name in R matrix, we can follow the below steps −

  • First of all, create a matrix with some columns having same name.

  • Then, use tapply along with colnames and sum function to find the row total of columns having same name.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(100,10),ncol=4)
colnames(M)lt;-c("C1","C1","C2","C2")
M

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

      C1 C1 C2 C2
[1,]  12 15  6 16
[2,]   2 12 13 10
[3,]   8 11 10 11
[4,]   9 11  6  9
[5,]  11 12  4 10
[6,]  12 12  8 12
[7,]  14  8  5  5
[8,]   9 15  9 13
[9,]   8 14  8  6
[10,]  8 14 16  7
[11,]  8 12 18 18
[12,] 18  8 15 12
[13,]  9 13 14 10
[14,]  8 11  8 10
[15,] 11 17 12  7
[16,]  8 13 12  6
[17,] 11 14  8 15
[18,] 12  6 10  6
[19,]  4  8 10  8
[20,] 17 13  7 16
[21,]  9  9 20  5
[22,] 12  8 13 14
[23,]  9 12 12  5
[24,]  7 14 13 13
[25,] 10  7  7 13

Find the row total of columns having same name

Using tapply along with colnames and sum function to find the row total of columns having same name in matrix M −

M<-matrix(rpois(100,10),ncol=4)
colnames(M)<-c("C1","C1","C2","C2")
t(apply(M,1, function(x) tapply(x,colnames(M),sum)))

Output

      C1 C2
[1,]  25 18
[2,]  21 20
[3,]  17 19
[4,]  25 14
[5,]  14 17
[6,]  27 20
[7,]  20 20
[8,]  23 23
[9,]  21 21
[10,] 16 19
[11,] 17 21
[12,] 29 18
[13,] 23 24
[14,] 21 19
[15,] 15 19
[16,] 18 17
[17,] 19 15
[18,] 22 16
[19,] 24 14
[20,] 23 25
[21,] 16 21
[22,] 24 20
[23,] 23 18
[24,] 20 23
[25,] 23 17

Updated on: 15-Nov-2021

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements