强制R输出为科学记数法,最多两位小数

问题描述 投票:22回答:2

我想为特定的R脚本提供一致的输出。在这种情况下,我希望所有数字输出都是科学记数法,正好有两位小数。

例子:

0.05 --> 5.00e-02
0.05671 --> 5.67e-02
0.000000027 --> 2.70e-08

我尝试使用以下选项:

options(scipen = 1)
options(digits = 2)

这给了我结果:

0.05 --> 0.05
0.05671 --> 0.057
0.000000027 --> 2.7e-08

我尝试时获得了相同的结果:

options(scipen = 0)
options(digits = 2)

谢谢你的任何建议。

r decimal scientific-notation
2个回答
44
投票

我认为最好使用formatC而不是改变全局设置。

对于您的情况,它可能是:

numb <- c(0.05, 0.05671, 0.000000027)
formatC(numb, format = "e", digits = 2)

产量:

[1] "5.00e-02" "5.67e-02" "2.70e-08"

1
投票

另一种选择是使用scientific库中的scales

library(scales)
numb <- c(0.05, 0.05671, 0.000000027)

# digits = 3 is the default but I am setting it here to be explicit,
# and draw attention to the fact this is different than the formatC
# solution.
scientific(numb, digits = 3)

## [1] "5.00e-02" "5.67e-02" "2.70e-08"

注意,digits设置为3,而不是formatC的情况

© www.soinside.com 2019 - 2024. All rights reserved.