How to divide the row values by row mean in R matrix?

R ProgrammingServer Side ProgrammingProgramming

To divide matrix row values by row mean 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 mean.

Create the matrix

Let’s create a matrix as shown below −

 Live Demo

M<-matrix(sample(1:10,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,] 9 1 5
[2,] 1 7 5
[3,] 6 7 5
[4,] 6 2 6
[5,] 9 8 7
[6,] 5 7 1
[7,] 9 5 1
[8,] 4 9 4
[9,] 10 2 6
[10,] 3 2 6
[11,] 2 5 1
[12,] 10 2 7
[13,] 4 8 1
[14,] 9 2 4
[15,] 2 1 7
[16,] 3 9 6
[17,] 7 10 7
[18,] 6 4 3
[19,] 2 10 6
[20,] 10 4 10
[21,] 8 5 8
[22,] 9 4 10
[23,] 10 7 1
[24,] 1 2 6
[25,] 2 10 8

Divide the matrix row values by row mean

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

 Live Demo

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

Output

        [,1]       [,2]     [,3]
[1,] 1.8000000 0.2000000 1.0000000
[2,] 0.2307692 1.6153846 1.1538462
[3,] 1.0000000 1.1666667 0.8333333
[4,] 1.2857143 0.4285714 1.2857143
[5,] 1.1250000 1.0000000 0.8750000
[6,] 1.1538462 1.6153846 0.2307692
[7,] 1.8000000 1.0000000 0.2000000
[8,] 0.7058824 1.5882353 0.7058824
[9,] 1.6666667 0.3333333 1.0000000
[10,] 0.8181818 0.5454545 1.6363636
[11,] 0.7500000 1.8750000 0.3750000
[12,] 1.5789474 0.3157895 1.1052632
[13,] 0.9230769 1.8461538 0.2307692
[14,] 1.8000000 0.4000000 0.8000000
[15,] 0.6000000 0.3000000 2.1000000
[16,] 0.5000000 1.5000000 1.0000000
[17,] 0.8750000 1.2500000 0.8750000
[18,] 1.3846154 0.9230769 0.6923077
[19,] 0.3333333 1.6666667 1.0000000
[20,] 1.2500000 0.5000000 1.2500000
[21,] 1.1428571 0.7142857 1.1428571
[22,] 1.1739130 0.5217391 1.3043478
[23,] 1.6666667 1.1666667 0.1666667
[24,] 0.3333333 0.6666667 2.0000000
[25,] 0.3000000 1.5000000 1.2000000
raja
Published on 04-Aug-2021 11:00:47
Advertisements