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

Forcing R output to be scientific notation with at most two decimals

我希望为特定的 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)

感谢您的任何建议。

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

另一种选择是使用 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