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

user1830307 picture user1830307 · Sep 21, 2016 · Viewed 50.2k times · Source

I would like to have consistent output for a particular R script. In this case, I would like all numeric output to be in scientific notation with exactly two decimal places.

Examples:

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

I tried using the following options:

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

This gave me the results:

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

I obtained the same results when I tried:

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

Thank you for any advice.

Answer

Dave Gruenewald picture Dave Gruenewald · Sep 21, 2016

I think it would probably be best to use formatC rather than change global settings.

For your case, it could be:

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

Which yields:

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