How to divide matrix values by row variance in R?

R ProgrammingServer Side ProgrammingProgramming

To divide matrix row values by row variance in R, we can follow the below steps −

  • First of all, create a matrix.
  • Then, use apply function to divide the matrix row values by row variance.

Create the matrix

Let's create a matrix as shown below −

 Live Demo

M<-matrix(sample(1:20,75,replace=TRUE),ncol=3)
M

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

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

Divide the matrix row values by row variance

Using apply function to divide the row values of M by row variance −

 Live Demo

M<-matrix(sample(1:20,75,replace=TRUE),ncol=3)
M_new<-t(apply(M,1, function(x) x/var(x)))
M_new

Output

         [,1]       [,2]       [,3]
[1,] 0.26530612 0.04081633 0.30612245
[2,] 0.43548387 0.38709677 0.14516129
[3,] 0.57692308 1.03846154 0.69230769
[4,] 0.29081633 0.07653061 0.29081633
[5,] 0.32432432 0.35135135 0.05405405
[6,] 2.53846154 1.84615385 1.61538462
[7,] 0.04972376 0.29834254 0.11602210
[8,] 0.13761468 0.46788991 0.33027523
[9,] 0.26582278 0.64556962 0.53164557
[10,] 0.05263158 0.23684211 0.02631579
[11,] 0.32374101 0.04316547 0.10791367
[12,] 0.02325581 0.32558140 0.20930233
[13,] 0.04633205 0.22007722 0.02316602
[14,] 0.49484536 0.40206186 0.15463918
[15,] 2.81250000 2.81250000 3.56250000
[16,] 0.32432432 0.02702703 0.05405405
[17,] 0.32967033 0.52747253 0.16483516
[18,] 0.09045226 0.06030151 0.28643216
[19,] 2.68421053 1.89473684 2.36842105
[20,] 2.00000000 3.00000000 3.00000000
[21,] 0.19402985 0.02985075 0.26865672
[22,] 0.22959184 0.01530612 0.22959184
[23,] 0.02325581 0.32558140 0.20930233
[24,] 1.61538462 0.92307692 1.84615385
[25,] 0.19917012 0.01244813 0.21161826
raja
Published on 10-Aug-2021 08:37:56
Advertisements