71

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.

  • 3
    You were almost there: `options(digits = 3, scipen = -2)`. I deleted this as an answer though because I don't know if you have really large numbers - this will not work for that. It would be better if someone else knew a really comprehensive way to do this across number types, but in a pinch and if you only have small numbers, this will do it. – HFBrowning Sep 21 '16 at 19:38

2 Answers2

110

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"
Dave Gruenewald
  • 5,329
  • 1
  • 23
  • 35
13

Another option is to use the scientific function from the scales library.

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"

Note, digits is set to 3, not 2 as is the case for formatC

steveb
  • 5,382
  • 2
  • 27
  • 36