Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write numbers in scientific notation in R

Tags:

r

xtable

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.

like image 673
R. Saeiti Avatar asked Feb 06 '23 09:02

R. Saeiti


1 Answers

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.

like image 80
Roland Avatar answered Feb 07 '23 23:02

Roland