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

31 r scientific-notation decimal

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

例子:

0.05 --> 5.00e-02
0.05671 --> 5.67e-02
0.000000027 --> 2.70e-08
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下选项:

options(scipen = 1)
options(digits = 2)
Run Code Online (Sandbox Code Playgroud)

这给了我结果:

0.05 --> 0.05
0.05671 --> 0.057
0.000000027 --> 2.7e-08
Run Code Online (Sandbox Code Playgroud)

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

options(scipen = 0)
options(digits = 2)
Run Code Online (Sandbox Code Playgroud)

谢谢你的任何建议.

Dav*_*ald 54

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

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

numb <- c(0.05, 0.05671, 0.000000027)
formatC(numb, format = "e", digits = 2)
Run Code Online (Sandbox Code Playgroud)

产量:

[1] "5.00e-02" "5.67e-02" "2.70e-08"
Run Code Online (Sandbox Code Playgroud)


ste*_*veb 7

另一种选择是使用scientificscales库。

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"
Run Code Online (Sandbox Code Playgroud)

注意,digits设置为 3,而不是 2formatC