【问题标题】:Rounding numbers in R to specified number of digits将 R 中的数字四舍五入到指定的位数
【发布时间】:2011-10-06 23:51:04
【问题描述】:

我在 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 位小数的有理数。

【问题讨论】:

    标签: r rounding


    【解决方案1】:

    要对数字格式进行精细控制,请尝试formatC()

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

    【讨论】:

    • 唯一的缺点就是输出的是一个字符。所以通常需要 as.numeric() 作为格式语句的包装器。
    • 但是您无法控制numerics 的显示方式。 as.numeric(formatC(9.50863385275955e-05, format = "f", digits = 8)) 在我的系统上显示为 9.509e-05,这显然不是我们想要的。
    • @MichaelHoffman - 您可以使用 options(scipen = XXX) 更改此行为,其中较大的 XXX 数字打印更多小数。
    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 1970-01-01
      • 2023-02-05
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      相关资源
      最近更新 更多