4

I am wondering if there is a way to write 0.000523 in scientific notation ( 5.23x10-4) in R. I am using the xtable command to write a table into latex.

R. Saeiti
  • 89
  • 3
  • 11

2 Answers2

4

You can use sprintf like this:

x <- c(0.000523, -523)

sprintf("%.2fx10^{%d}", 
        x/10^floor(log10(abs(x))), 
        floor(log10(abs(x))))
#[1] "5.23x10^{-4}" "-5.23x10^{2}"

You'll need to write some ifelse conditions to have different formatting depending on the decimal ranges.

Roland
  • 127,288
  • 10
  • 191
  • 288
  • what about `gsub("e", "x10^", format(scientific = T, x))` giving `5.23x10^-04`. though not logically sound step – joel.wilson Jan 06 '17 at 10:24
4

The xtable package offers the function sanitize.numbers() that can do this. It works on characters, so you first have to use format() to convert your numbers to characters:

library(xtable)
sanitize.numbers(format(0.000523, scientific = TRUE),
                 type = "latex", math.style.exponents = TRUE)
## [1] "$5.23 \\times 10^{-4}$"

As you notice, this does not give 5.23x10^-4 but rather the equivalent of this expression in LaTeX notation, which may not be what you needed.

Stibu
  • 15,166
  • 6
  • 57
  • 71