要将矩阵中的行值转换为行百分比,我们可以找到行总和,然后将每个行值除以该总和。例如,如果我们有一个名为M的矩阵,则可以使用以下命令将M中的行值转换为行百分比
round((M/rowSums(M))*100,2)
考虑下面的矩阵-
M1<-matrix(rpois(80,8),ncol=4) M1输出结果
[,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
查找M1中每个值的行百分比-
round((M1/rowSums(M1))*100,2)输出结果
[,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
M2<-matrix(rpois(40,8),ncol=2) M2输出结果
[,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
查找M2中每个值的行百分比-
round((M2/rowSums(M2))*100,2)输出结果
[,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