如何在R中的矩阵中找到行,列和总数的总和?
通过分别使用函数rowSums,colSums和sum,可以简单地找到矩阵中行,列和总数的总和。行总和,列总和和总计是最常用的比较分析工具,例如方差分析,卡方检验等。
例1
M1<−matrix(1:25,nrow=5)输出结果M1
[,1] [,2] [,3] [,4] [,5][1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
示例
rowSums(M1)输出结果
[1] 55 60 65 70 75
示例
colSums(M1)输出结果
[1] 15 40 65 90 115
示例
sum(M1)输出结果
[1] 325
例2
M2<−matrix(rpois(64,5),nrow=8)输出结果M2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8][1,] 3 7 6 3 8 4 4 4
[2,] 5 4 6 5 4 6 5 4
[3,] 7 4 3 6 4 2 6 4
[4,] 4 7 4 3 11 3 7 4
[5,] 3 4 11 9 3 4 4 3
[6,] 3 10 3 3 5 8 6 2
[7,] 9 2 3 4 6 6 3 4
[8,] 7 8 1 5 6 7 5 3
示例
rowSums(M2)输出结果
[1] 39 39 36 43 41 40 37 42
示例
colSums(M2)输出结果
[1] 41 46 37 38 47 40 40 28
示例
sum(M2)输出结果
[1] 317
范例3
M3<−matrix(rpois(100,8),nrow=20)输出结果M3
[,1] [,2] [,3] [,4] [,5]输出结果[1,] 5 11 12 5 11
[2,] 7 7 9 8 10
[3,] 15 11 8 11 7
[4,] 9 3 7 12 7
[5,] 6 9 4 4 7
[6,] 10 8 7 8 4
[7,] 14 6 6 7 9
[8,] 6 5 5 10 7
[9,] 8 7 3 7 10
[10,] 12 7 5 11 8
[11,] 8 10 9 11 10
[12,] 4 7 9 9 12
[13,] 9 8 15 10 6
[14,] 6 4 9 7 6
[15,] 7 10 7 7 9
[16,] 10 11 8 7 7
[17,] 9 6 12 6 9
[18,] 5 8 8 7 6
[19,] 5 7 3 3 8
[20,] 12 7 9 7 10
rowSums(M3)
示例
[1] 44 41 52 38 30 37 42 33 35 43 48 41 48 32 40 43 42 34 26 45
示例
colSums(M3)输出结果
[1] 167 152 155 157 163
示例
sum(M3)输出结果
[1] 794
例子4
M4<−matrix(rnorm(80),nrow=20)输出结果M4
[,1] [,2] [,3] [,4][1,] 0.3188698 0.81972400 1.196668896 −0.1600363
[2,] 1.1626229 0.58996464 −0.936554585 1.1429420
[3,] −0.5603425 −1.76147185 0.287399797 0.4585298
[4,] −0.9019506 −0.23604072 −1.034877755 1.0206584
[5,] −0.5248356 1.05424991 −0.645217913 −0.4739691
[6,] −1.5610909 −0.20283113 0.996732180 −0.7709547
[7,] 0.2476689 0.76585019 −2.972610580 −0.2166821
[8,] −0.6014235 −0.80808451 −1.318205769 0.5311314
[9,] −0.5758808 1.00178363 0.030445943 0.9135367
[10,] 0.1207577 1.10829807 −0.057548495 0.2686915
[11,] 1.3505622 0.21916808 −0.521492576 0.2863660
[12,] −1.0845436 0.81589145 −0.316661626 −0.6171679
[13,] 0.6450188 1.22799788 −0.625778034 0.6154738
[14,] −2.9332291 1.09912124 0.274039557 0.5219165
[15,] 1.3656969 −1.91670352 1.099289293 0.1918600
[16,] −1.3845404 1.56674213 0.951188176 −0.2644617
[17,] −1.4644000 −0.02311353 0.006714121 0.2755697
[18,] −0.8878274 −1.08802913 1.098809046 −0.8005284
[19,] −0.6842826 0.05200371 0.488929737 1.7782674
[20,] 1.9084408 1.73997571 −0.419218542 −0.9593852
示例
rowSums(M4)输出结果
[1] 2.1752264 1.9589749 −1.5758848 −1.1522107 −0.5897728 −1.5381445[7] −2.1757735 −2.1965824 1.3698855 1.4401988 1.3346037 −1.2024817
[13] 1.8627125 −1.0381517 0.7401427 0.8689281 −1.2052297 −1.6775759
[19] 1.6349182 2.2698128
示例
colSums(M4)输出结果
[1] −6.044709 6.024496 −2.417949 3.741758
示例
sum(M4)输出结果
[1] 1.303596
以上是 如何在R中的矩阵中找到行,列和总数的总和? 的全部内容, 来源链接: utcz.com/z/319980.html