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

3

75

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.

Redemption answered 21/9, 2016 at 18:7 Comment(1)
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.Scholem
J
119

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"
Joachima answered 21/9, 2016 at 19:36 Comment(0)
N
15

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

Nicknack answered 5/9, 2018 at 22:7 Comment(0)
C
0

There are a few different ways to do this as mentioned in this thread and here. Just putting it all together and thanking the original authors @Dave, @steveb and others.

> numb <- c(0.05, 0.05671, 0.000000027)

> # method 1: change the global display options (which might not be usefull everytime) 
> options(digits=3) #change global display options
> numb
[1] 5.00e-02 5.67e-02 2.70e-08

> # method 2: gives the output in character format
> formatC(numb, format = "e", digits = 2)
[1] "5.00e-02" "5.67e-02" "2.70e-08"
> typeof(formatC(numb, format = "e", digits = 2))
[1] "character"

# method 3: again the output is in character format
> sprintf("%.1e", numb)
[1] "5.0e-02" "5.7e-02" "2.7e-08"

# method 4: using library(scales), again the output is in character format
enter code here
> scales::scientific(numb, digits = 3)
[1] "5.00e-02" "5.67e-02" "2.70e-08"
Corsage answered 5/2 at 15:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.