How to convert the row values in a matrix to row percentage in R?


To convert the row values in a matrix to row percentage, we can find the row sums and divide each row value by this sum. For example, if we have a matrix called M then we can convert the row values in M to row percentage by using the command

round((M/rowSums(M))*100,2)

Example

Consider the below matrix −

 Live Demo

M1<-matrix(rpois(80,8),ncol=4)
M1

Output

     [,1] [,2] [,3] [,4]
[1,]  3    4    7    7
[2,] 10    9    7    9
[3,] 13    7    9   10
[4,]  7   13   10   12
[5,]  2   11    8   10
[6,]  6    9   11    9
[7,] 11    8   14    4
[8,]  7    7    9    7
[9,]  3    9    8   12
[10,] 6    7    4    8
[11,] 9    7    3    6
[12,] 11  13   12    9
[13,] 8   12    7   12
[14,] 5   6     9   11
[15,] 9   7     9    8
[16,] 9   9     6    7
[17,] 6  10     6    7
[18,] 8   9     4   15
[19,] 8   6     7   10
[20,] 6   5     7    4

Finding the row percentages for each value in M1 −

Example

round((M1/rowSums(M1))*100,2)

Output

      [,1]    [,2]   [,3]   [,4]
[1,]  14.29  19.05  33.33   33.33
[2,]  28.57  25.71  20.00   25.71
[3,]  33.33  17.95  23.08   25.64
[4,]  16.67  30.95  23.81   28.57
[5,]  6.45   35.48  25.81   32.26
[6,]  17.14  25.71  31.43   25.71
[7,]  29.73  21.62  37.84   10.81
[8,]  23.33  23.33  30.00   23.33
[9,]  9.38   28.12  25.00   37.50
[10,] 24.00  28.00  16.00   32.00
[11,] 36.00  28.00  12.00   24.00
[12,] 24.44  28.89  26.67   20.00
[13,] 20.51  30.77  17.95   30.77
[14,] 16.13  19.35  29.03   35.48
[15,] 27.27  21.21  27.27   24.24
[16,] 29.03  29.03  19.35   22.58
[17,] 20.69  34.48  20.69   24.14
[18,] 22.22  25.00  11.11    41.67
[19,] 25.81  19.35  22.58   32.26
[20,] 27.27  22.73  31.82   18.18

Example

 Live Demo

M2<-matrix(rpois(40,8),ncol=2)
M2

Output

      [,1] [,2]
[1,]  13   11
[2,]   5   12
[3,]   7    9
[4,]   8    4
[5,]   4    6
[6,]  10    7
[7,]   6    7
[8,]   6    5
[9,]  14    4
[10,]  6    8
[11,]  7   11
[12,]  8    9
[13,]  9    2
[14,] 13   16
[15,]  6    7
[16,] 11    7
[17,]  4    4
[18,] 16   11
[19,]  7    7
[20,] 10    6

Finding the row percentages for each value in M2 −

Example

round((M2/rowSums(M2))*100,2)

Output

       [,1]   [,2]
[1,]  54.17  45.83
[2,]  29.41  70.59
[3,]  43.75  56.25
[4,]  66.67  33.33
[5,]  40.00  60.00
[6,]  58.82  41.18
[7,]  46.15  53.85
[8,]  54.55  45.45
[9,]  77.78  22.22
[10,] 42.86  57.14
[11,] 38.89  61.11
[12,] 47.06  52.94
[13,] 81.82  18.18
[14,] 44.83  55.17
[15,] 46.15  53.85
[16,] 61.11  38.89
[17,] 50.00  50.00
[18,] 59.26  40.74
[19,] 50.00  50.00
[20,] 62.50  37.50

Updated on: 16-Mar-2021

668 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements