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

R ProgrammingServer Side ProgrammingProgramming

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

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

Divide the matrix row values by row minimum

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

 Live Demo

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

Output

          [,1]      [,2]     [,3]
[1,]  16.000000  1.000000  18.000000
[2,]  18.000000  12.000000 1.000000
[3,]  1.000000   1.583333  1.583333
[4,]  3.500000   1.000000  9.000000
[5,]  1.000000   1.400000  1.600000
[6,]  2.000000   1.000000  2.000000
[7,]  3.750000   3.500000  1.000000
[8,]  2.000000   1.000000  17.000000
[9,]  1.375000   1.500000  1.000000
[10,] 1.833333   3.166667  1.000000
[11,] 4.000000   1.000000 3.500000
[12,] 8.000000   14.000000 1.000000
[13,] 1.000000   3.800000 3.600000
[14,] 2.833333   2.333333 1.000000
[15,] 1.083333   1.000000 1.500000
[16,] 1.000000   19.000000 14.000000
[17,] 1.000000   2.111111 1.888889
[18,] 1.666667   1.833333 1.000000
[19,] 1.500000   1.000000 1.000000
[20,] 2.000000   1.666667 1.000000
[21,] 1.000000   1.636364 1.000000
[22,] 1.000000   4.750000 1.750000
[23,] 1.000000   3.000000 6.333333
[24,] 1.714286   1.000000 2.714286
[25,] 2.500000   2.500000 1.000000
raja
Published on 02-Aug-2021 12:59:56
Advertisements