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

72

我希望一份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)

感谢任何建议。


3
您已经接近成功了:options(digits = 3, scipen = -2)。但我删除了这个答案,因为我不知道您是否有非常大的数字——该方法不能处理那样的数字。如果有其他人知道跨数值类型进行此操作的全面方法,则最好使用该方法。但是,在紧要关头和只有小数字的情况下,这个方法就能胜任。 - HFBrowning
2个回答

111

我认为最好使用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"

14

另一个选择是使用 scales 库中的 scientific 函数。

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的情况下为2。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接