How to write numbers in scientific notation in R

3k views Asked by At

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.

2

There are 2 answers

1
Roland On

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.

0
Stibu On

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.