How to divide matrix rows by number of columns in R?

R ProgrammingServer Side ProgrammingProgramming

To divide matrix rows by number of columns in R, we can follow the below steps −

  • First of all, create a matrix.
  • Then, use apply function to divide the matrix rows by number of columns.

Create the matrix

Let’s create a matrix as shown below −

 Live Demo

M<-matrix(sample(1:100,40),ncol=2)
M

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

    [,1] [,2]
[1,]  98 93
[2,] 83 86
[3,] 65 46
[4,] 31 8
[5,] 9 58
[6,] 62 51
[7,] 96 95
[8,] 48 92
[9,] 53 56
[10,] 40 16
[11,] 54 52
[12,] 100 27
[13,] 88 29
[14,] 18 33
[15,] 57 71
[16,] 90 28
[17,] 73 77
[18,] 97 24
[19,] 84 72
[20,] 75 1

Divide the matrix rows by number of columns

Using apply function to divide the rows of M by number of columns in M −

 Live Demo

M<-matrix(sample(1:100,40),ncol=2)
M_new<-t(apply(M,1, function(x) x/length(x)))
M_new

Output

     [,1] [,2]
[1,] 49.0 46.5
[2,] 41.5 43.0
[3,] 32.5 23.0
[4,] 15.5 4.0
[5,] 4.5 29.0
[6,] 31.0 25.5
[7,] 48.0 47.5
[8,] 24.0 46.0
[9,] 26.5 28.0
[10,] 20.0 8.0
[11,] 27.0 26.0
[12,] 50.0 13.5
[13,] 44.0 14.5
[14,] 9.0 16.5
[15,] 28.5 35.5
[16,] 45.0 14.0
[17,] 36.5 38.5
[18,] 48.5 12.0
[19,] 42.0 36.0
[20,] 37.5 0.5
raja
Published on 07-Aug-2021 09:16:20
Advertisements