将R中的数字舍入到指定的位数

时间:2011-10-06 23:51:04

标签: r rounding

我在R中舍入数字时遇到问题。我有以下数据,我想将它们舍入为8位小数。

structure(c(9.50863385275955e-05, 4.05702267762077e-06, 2.78921491976249e-05, 
8.9107773737659e-05, 5.0672643927135e-06, 5.87776809485182e-05,
2.76421630542694e-05, 5.51662570625727e-05, 2.52790624570593e-05, 
2.00407457671806e-05, 8.33373482160056e-05, 7.8297940825207e-05,
2.00407457671806e-05, 8.33373482160056e-05, 7.8297940825207e-05,
2.00407457671806e-05, 8.33373482160056e-05, 7.8297940825207e-05
), .Names = c("CC/CC", "TT/CC", "CT/CC", "NC/CC", "CC/TT", "TT/TT",
"CT/TT", "NC/TT", "CC/CT", "TT/CT", "CT/CT", "NC/CT"))

这些数字是指数的形式,我想将它们转换为8位小数的有理数。

2 个答案:

答案 0 :(得分:14)

要精确控制数字格式,请尝试formatC()

res <- structure(c(9.50863385275955e-05, 4.05702267762077e-06), 
                 .Names = c("CC/CC", "TT/CC"))

formatC(res, format="f", digits=8)

答案 1 :(得分:5)

signif函数舍入到特定的有效位数(并且round函数舍入到特定的小数位数。)

res <- structure(c(9.50863385275955e-05, 4.05702267762077e-06), 
             .Names = c("CC/CC", "TT/CC"))
signif(res, digits=8)

请注意,打印结果取决于选项options(digits=7) ...您还可以直接指定digits参数print

print(pi, digits=3)  # 3.14
print(pi, digits=17) # 3.1415926535897931

以下是说明signifround之间差异的示例:

x <- c(pi, pi*1000, pi/1000)
round(x, 3) # 3.142 3141.593 0.003
signif(x, 3) # 3.14e+00 3.14e+03 3.14e-03