Search code examples
rscientific-notationsignificant-digits

Choose the power of 10 to display in R, for formatting error in scientific notation


I'm writing a program in R in order to estimate the value of a physical constant.

At the end of the program, after I get the result I wanted I'd like to put it in a plot in the format "value +- error".

In order to make that more readable I want the exponential to be the same in both the value and the error, but because the error is much smaller than the value, R automatically writes it with the closest power of 10.

Moreover, because it is an absolute error I'd like it to be with 1 significant digit.

How should I write the text command? I am currently writing

text(1000, 2.0e-06,paste("Carica specifica =",format(CS11, digits=4),"+-",formatC(ECS1[1], digits=1))) 

Which gives on screen:

"1.52e+11+-9e+09"

Instead I'd like to get something like:

"1.5e+11+-0.1+e11"

What should I write?


Solution

  • Calculate it yourself:

    x <- 1.52e11
    se <- 9e9
    e <- floor(log10(x))
    
    sprintf("Carica specifica = %.1fe+%d +- %.1fe+%d", x/10^e, e, se/10^e, e)
    #[1] "Carica specifica = 1.5e+11 +- 0.1e+11"
    

    This assumes that x >= 1. If that assumption is not valid, some slight modifications would be necessary.