Find Row Standard Deviation of Columns with Same Name in R Matrix



To find the row standard deviation 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 sd function to find the row standard deviation 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("C1","C2","C1","C2")
M

Output

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

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

Find the row standard deviation of columns having same name

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

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

Output

          C1       C2
[1,]  0.7071068 3.5355339
[2,]  4.2426407 0.0000000
[3,]  2.1213203 1.4142136
[4,]  0.7071068 1.4142136
[5,]  2.1213203 2.1213203
[6,]  2.8284271 4.9497475
[7,]  1.4142136 0.0000000
[8,]  1.4142136 0.0000000
[9,]  0.7071068 0.0000000
[10,] 1.4142136 0.7071068
[11,] 0.7071068 0.0000000
[12,] 2.1213203 2.1213203
[13,] 0.7071068 0.0000000
[14,] 0.0000000 0.7071068
[15,] 3.5355339 2.1213203
[16,] 0.0000000 1.4142136
[17,] 2.8284271 2.1213203
[18,] 2.1213203 2.1213203
[19,] 1.4142136 0.0000000
[20,] 0.0000000 1.4142136
[21,] 0.0000000 0.7071068
[22,] 2.1213203 2.1213203
[23,] 0.7071068 2.1213203
[24,] 0.0000000 2.1213203
[25,] 1.4142136 2.1213203
Updated on: 2021-11-15T07:03:52+05:30

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements