How to divide matrix rows by maximum value in each row excluding 0 in R?


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

  • First of all, create a matrix.
  • Then, use apply function and if else function to divide the matrix row values by row maximum excluding 0.

Create the matrix

Let's create a matrix as shown below −

 Live Demo

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

Divide the matrix row values by row maximum excluding 0

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

 Live Demo

M<-matrix(rpois(75,1),ncol=3)
M_new<-t(apply(M,1, function(x) if (0 %in% x) x else x/max(x)))
M_new

Output

      [,1]   [,2]     [,3]
[1,]  2.0 0.0000000 1.0000000
[2,]  1.0 2.0000000 0.0000000
[3,]  1.0 0.2500000 0.2500000
[4,]  2.0 1.0000000 0.0000000
[5,]  1.0 2.0000000 0.0000000
[6,]  0.0 2.0000000 0.0000000
[7,]  0.0 2.0000000 1.0000000
[8,]  2.0 1.0000000 0.0000000
[9,]  1.0 0.3333333 0.3333333
[10,] 0.5 1.0000000 0.5000000
[11,] 1.0 3.0000000 0.0000000
[12,] 1.0 2.0000000 0.0000000
[13,] 1.0 1.0000000 0.0000000
[14,] 0.0 1.0000000 1.0000000
[15,] 0.0 1.0000000 0.0000000
[16,] 1.0 0.5000000 0.5000000
[17,] 1.0 0.0000000 1.0000000
[18,] 0.0 1.0000000 1.0000000
[19,] 1.0 1.0000000 0.0000000
[20,] 0.0 0.0000000 2.0000000
[21,] 0.0 1.0000000 2.0000000
[22,] 1.0 1.0000000 0.0000000
[23,] 0.0 2.0000000 3.0000000
[24,] 2.0 0.0000000 1.0000000
[25,] 0.0 2.0000000 0.0000000

Updated on: 14-Aug-2021

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements