如何在R中对矩阵值进行四舍五入?


为了对矩阵值进行四舍五入,我们可以使用`round`函数。

例如,如果我们有一个名为M的矩阵,并且我们想使用以下命令将M中的值四舍五入到小数点后2位:

M<-round(M,3)

示例1

以下代码片段创建了一个示例矩阵:

M1<-matrix(rnorm(60),ncol=3)
M1

创建了以下矩阵:

            [,1]        [,2]        [,3]
[1,]  -1.0065099  0.42090379  0.16908864
[2,]  -0.9034180  0.04851710  1.99757669
[3,]   0.9446946 -0.64459616 -0.05651909
[4,]   0.8005215  0.83892594  0.20206176
[5,]  -1.3526208  1.01668769  0.24246712
[6,]   0.8749366 -0.97465448 -2.08143783
[7,]   0.4345922  0.09487058 -0.44182193
[8,]  -0.9510890 -0.66812782  0.57973760
[9,]  -0.9277041  1.70982550  1.86352019
[10,] -0.4996847  1.95912699  0.43636559
[11,] -0.4127734 -0.88863671  0.28843873
[12,] -0.7470326  0.37128013 -2.03441389
[13,] -0.9018772 -0.29365294 -0.25490999
[14,] -1.0672464  1.90360060 -0.37672929
[15,]  0.1210364 -0.76459234 -0.39797807
[16,] -0.1184469  1.26720271  0.73788208
[17,]  0.1479814 -0.97256445 -1.59624932
[18,]  1.2248650  0.14759500  1.37837572
[19,]  1.6743637  0.14866853  0.24055145
[20,]  0.5748317  0.07914620  0.46610331

为了将上面创建的数据框中M1中的值四舍五入到小数点后三位,请将以下代码添加到上面的代码片段中:

M1<-matrix(rnorm(60),ncol=3)
M1<-round(M1,3)
M1

输出

如果您将以上所有代码片段作为一个程序执行,它将生成以下输出:

        [,1]   [,2]   [,3]
[1,]  -1.007  0.421  0.169
[2,]  -0.903  0.049  1.998
[3,]   0.945 -0.645 -0.057
[4,]   0.801  0.839  0.202
[5,]  -1.353  1.017  0.242
[6,]   0.875 -0.975 -2.081
[7,]   0.435  0.095 -0.442
[8,]  -0.951 -0.668  0.580
[9,]  -0.928  1.710  1.864
[10,] -0.500  1.959  0.436
[11,] -0.413 -0.889  0.288
[12,] -0.747  0.371 -2.034
[13,] -0.902 -0.294 -0.255
[14,] -1.067  1.904 -0.377
[15,]  0.121 -0.765 -0.398
[16,] -0.118  1.267  0.738
[17,]  0.148 -0.973 -1.596
[18,]  1.225  0.148  1.378
[19,]  1.674  0.149  0.241
[20,]  0.575  0.079  0.466

示例2

以下代码片段创建了一个示例矩阵:

M2<-matrix(runif(40,2,5),ncol=2)
M2

创建了以下矩阵:

          [,1]     [,2]
[1,]  4.200955 3.384460
[2,]  4.677737 2.837406
[3,]  3.769280 3.849745
[4,]  2.969764 2.735219
[5,]  4.144210 2.135855
[6,]  2.826166 2.846861
[7,]  3.038215 3.732255
[8,]  3.452157 3.116253
[9,]  2.635194 3.037327
[10,] 2.573566 4.542331
[11,] 4.441132 4.298901
[12,] 3.996963 4.486278
[13,] 2.829070 4.067829
[14,] 4.722787 3.762698
[15,] 2.624773 4.173573
[16,] 2.425940 3.745760
[17,] 2.388542 2.652648
[18,] 2.845289 2.322316
[19,] 4.001353 4.301136
[20,] 2.827143 4.986207

为了将上面创建的数据框中M2中的值四舍五入到小数点后两位,请将以下代码添加到上面的代码片段中:

M2<-matrix(runif(40,2,5),ncol=2)
M2<-round(M2,2)
M2

输出

如果您将以上所有代码片段作为一个程序执行,它将生成以下输出:

       [,1] [,2]
[1,]  4.20 3.38
[2,]  4.68 2.84
[3,]  3.77 3.85
[4,]  2.97 2.74
[5,]  4.14 2.14
[6,]  2.83 2.85
[7,]  3.04 3.73
[8,]  3.45 3.12
[9,]  2.64 3.04
[10,] 2.57 4.54
[11,] 4.44 4.30
[12,] 4.00 4.49
[13,] 2.83 4.07
[14,] 4.72 3.76
[15,] 2.62 4.17
[16,] 2.43 3.75
[17,] 2.39 2.65
[18,] 2.85 2.32
[19,] 4.00 4.30
[20,] 2.83 4.99

更新于:2021年11月5日

3K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告