Search code examples
rr-markdownquartogt

Format printing of small numbers in scientific notation to use the same power


I have column in dataframe containing:

dat <- c(1.664140e-07, 2.988795e-07, 3.501572e-07, -3.790459e-07, 1.839657e-07, -3.303678e-08, 1.232856e-07, 3.652545e-07, -4.180682e-09, 6.088182e-08, 1.542207e-07, 1.015173e-07, 4.423879e-07, 1.729282e-07, 8.462837e-08, 2.670472e-07, 3.364679e-07, 2.827205e-07)

I want to format it for printing in the report. When I use:

formated <- format(dat, digits = 4, scientific = TRUE, nsmall = 4)

I've got:

[1] " 1.664e-07" " 2.989e-07" " 3.502e-07" "-3.790e-07" " 1.840e-07" "-3.304e-08" " 1.233e-07" " 3.653e-07" "-4.181e-09" " 6.088e-08"
[11] " 1.542e-07" " 1.015e-07" " 4.424e-07" " 1.729e-07" " 8.463e-08" " 2.670e-07" " 3.365e-07" " 2.827e-07"

For consistency with other tables that have lover variance (same power -07) I need a way to format it like this:

[1] " 1.664e-07" " 2.989e-07" " 3.502e-07" "-3.790e-07" " 1.840e-07" **"-0.330e-07"** " 1.233e-07" " 3.653e-07" **"-0.041e-07"** **" 0.608e-07"**
[11] " 1.542e-07" " 1.015e-07" " 4.424e-07" " 1.729e-07" **"0.846e-07"** " 2.670e-07" " 3.365e-07" " 2.827e-07"

Yes. I know that it is not a proper scientific notation. But for the audience the report is intended it will be much more clear to see what is the difference between this series and other three.

Preferably I work with gt package but I'm flexible in this matter.


Solution

  • Here is something quick:

    foo <- function(x) sprintf("%.3fe-07", x * 1e7)
    foo(dat)
    #  [1] "1.664e-07"  "2.989e-07"  "3.502e-07"  "-3.790e-07" "1.840e-07"  "-0.330e-07" "1.233e-07" 
    #  [8] "3.653e-07"  "-0.042e-07" "0.609e-07"  "1.542e-07"  "1.015e-07"  "4.424e-07"  "1.729e-07" 
    # [15] "0.846e-07"  "2.670e-07"  "3.365e-07"  "2.827e-07"