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

R ProgrammingServer Side ProgrammingProgramming

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

Example

Create the matrix

Let’s create a matrix as shown below −

M<-matrix(rpois(100,2),ncol=4)
colnames(M)<-c("x1","x1","x2","x2")
M

Output

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

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

Find the row variance of columns having same name

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

M<-matrix(rpois(100,2),ncol=4)
colnames(M)<-c("x1","x1","x2","x2")
t(apply(M,1, function(x) tapply(x,colnames(M),var)))

Output

      x1   x2
[1,]  2.0 8.0
[2,]  0.5 2.0
[3,]  0.5 0.0
[4,]  0.5 0.5
[5,]  0.5 0.5
[6,]  0.5 0.5
[7,]  0.5 4.5
[8,]  4.5 2.0
[9,]  2.0 0.5
[10,] 0.5 0.0
[11,] 0.0 0.5
[12,] 2.0 0.0
[13,] 2.0 0.5
[14,] 2.0 0.5
[15,] 2.0 0.5
[16,] 0.5 0.5
[17,] 0.5 2.0
[18,] 0.0 2.0
[19,] 4.5 0.0
[20,] 2.0 2.0
[21,] 0.5 2.0
[22,] 2.0 0.5
[23,] 2.0 0.5
[24,] 0.5 0.5
[25,] 2.0 0.5
raja
Updated on 09-Nov-2021 06:05:15

Advertisements