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


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

Create the matrix

Let’s create a matrix as shown below −

 Live Demo

M<-matrix(sample(1:100,75),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,] 29 69 82
[2,] 60 22 87
[3,] 86 49 16
[4,] 66 14 96
[5,] 19 92 13
[6,] 90 80 35
[7,] 32 3 30
[8,] 44 2 59
[9,] 24 54 97
[10,] 75 37 70
[11,] 31 58 38
[12,] 76 72 55
[13,] 94 81 95
[14,] 18 28 1
[15,] 78 33 61
[16,] 63 25 93
[17,] 4 47 46
[18,] 21 42 68
[19,] 71 57 62
[20,] 43 12 64
[21,] 40 73 99
[22,] 84 5 15
[23,] 39 56 27
[24,] 45 100 98
[25,] 88 11 7

Divide the matrix row values by row sum

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

 Live Demo

M<-matrix(sample(1:100,75),ncol=3)
M_new<-t(apply(M,1, function(x) x/sum(x)))
M_new

Output

[,1] [,2] [,3]
[1,] 0.16111111 0.38333333 0.45555556
[2,] 0.35502959 0.13017751 0.51479290
[3,] 0.56953642 0.32450331 0.10596026
[4,] 0.37500000 0.07954545 0.54545455
[5,] 0.15322581 0.74193548 0.10483871
[6,] 0.43902439 0.39024390 0.17073171
[7,] 0.49230769 0.04615385 0.46153846
[8,] 0.41904762 0.01904762 0.56190476
[9,] 0.13714286 0.30857143 0.55428571
[10,] 0.41208791 0.20329670 0.38461538
[11,] 0.24409449 0.45669291 0.29921260
[12,] 0.37438424 0.35467980 0.27093596
[13,] 0.34814815 0.30000000 0.35185185
[14,] 0.38297872 0.59574468 0.02127660
[15,] 0.45348837 0.19186047 0.35465116
[16,] 0.34806630 0.13812155 0.51381215
[17,] 0.04123711 0.48453608 0.47422680
[18,] 0.16030534 0.32061069 0.51908397
[19,] 0.37368421 0.30000000 0.32631579
[20,] 0.36134454 0.10084034 0.53781513
[21,] 0.18867925 0.34433962 0.46698113
[22,] 0.80769231 0.04807692 0.14423077
[23,] 0.31967213 0.45901639 0.22131148
[24,] 0.18518519 0.41152263 0.40329218
[25,] 0.83018868 0.10377358 0.06603774

Updated on: 14-Aug-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements