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

R ProgrammingServer Side ProgrammingProgramming

To find the row mean 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 mean function to find the row mean of columns having same name.

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(100,5),ncol=4)
colnames(M)<-c("A","B","B","A")
M

Output

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

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

Find the row mean of columns having same name

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

M<-matrix(rpois(100,5),ncol=4)
colnames(M)<-c("A","B","B","A")
t(apply(M,1, function(x) tapply(x,colnames(M),mean)))

Output

       A   B
[1,]  4.5 6.0
[2,]  6.0 3.0
[3,]  4.0 4.5
[4,]  6.5 3.5
[5,]  4.5 6.5
[6,]  5.0 5.0
[7,]  4.5 5.0
[8,]  5.0 3.0
[9,]  7.0 6.0
[10,] 3.0 6.0
[11,] 2.0 6.5
[12,] 4.0 7.0
[13,] 6.5 3.5
[14,] 4.5 3.0
[15,] 7.5 2.5
[16,] 8.0 8.0
[17,] 4.0 5.0
[18,] 9.0 8.5
[19,] 4.0 3.5
[20,] 4.0 3.0
[21,] 6.0 3.5
[22,] 6.5 4.0
[23,] 4.0 3.5
[24,] 2.5 3.0
[25,] 2.0 3.5
raja
Updated on 15-Nov-2021 06:56:45

Advertisements