Rounding numbers in R to specified number of digits

不想你离开。 提交于 2019-12-17 07:34:10

问题


I have a problem in rounding numbers in R. I have the following data, and I want to round them to 8 decimal digits.

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"))

These digits are in the form of exponent and I want to convert them to rational numbers with 8 decimal places.


回答1:


For fine control over formatting of numbers, try formatC()

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

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



回答2:


The signif function rounds to a specific number of significant digits (and the round function rounds to a specific number of decimals).

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

Note that printing the result depends on an option, options(digits=7)... You can also directly specify the digits argument to print:

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

Here's an example illustrating the difference between signif and round:

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


来源:https://stackoverflow.com/questions/7681756/rounding-numbers-in-r-to-specified-number-of-digits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!