Syntax error How to divide the matrix rows by row maximum in R?

How to divide the matrix rows by row maximum in R?



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

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

Divide the matrix row values by row maximum

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

 Live Demo

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

Output

         [,1]      [,2]    [,3]
[1,] 1.0000000 0.5555556 0.6666667
[2,] 1.0000000 0.2000000 0.5000000
[3,] 0.5714286 1.0000000 0.7142857
[4,] 1.0000000 0.1000000 0.4000000
[5,] 1.0000000 0.2000000 0.8000000
[6,] 1.0000000 0.3750000 0.1250000
[7,] 0.4000000 1.0000000 1.0000000
[8,] 0.4444444 0.4444444 1.0000000
[9,] 0.6666667 1.0000000 0.7777778
[10,] 0.2857143 1.0000000 1.0000000
[11,] 1.0000000 0.5555556 0.4444444
[12,] 1.0000000 1.0000000 0.2000000
[13,] 1.0000000 0.3333333 0.5000000
[14,] 1.0000000 0.6000000 0.8000000
[15,] 1.0000000 0.7777778 0.6666667
[16,] 0.8750000 0.6250000 1.0000000
[17,] 0.1000000 0.8000000 1.0000000
[18,] 0.6000000 1.0000000 0.2000000
[19,] 0.8000000 0.6000000 1.0000000
[20,] 0.4000000 0.3000000 1.0000000
[21,] 0.8333333 0.8333333 1.0000000
[22,] 0.6000000 0.7000000 1.0000000
[23,] 0.8888889 0.1111111 1.0000000
[24,] 0.3000000 0.9000000 1.0000000
[25,] 0.4000000 0.6000000 1.0000000
Updated on: 2021-08-13T11:09:01+05:30

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements