Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing R output to be scientific notation with at most two decimals

People also ask

How do you change to scientific notation in R?

Global options of your R workspace. Use options(scipen = n) to display numbers in scientific format or fixed. Positive values bias towards fixed and negative towards scientific notation. You can reset this option with options(scipen = 0) .

How do you avoid large numbers in scientific notation in R?

If you want to avoid scientific notation for a given number or a series of numbers, you can use the format() function by passing scientific = FALSE as an argument.


I think it would probably be best to use formatC rather than change global settings.

For your case, it could be:

numb <- c(0.05, 0.05671, 0.000000027)
formatC(numb, format = "e", digits = 2)

Which yields:

[1] "5.00e-02" "5.67e-02" "2.70e-08"

Another option is to use the scientific from the scales library.

library(scales)
numb <- c(0.05, 0.05671, 0.000000027)

# digits = 3 is the default but I am setting it here to be explicit,
# and draw attention to the fact this is different than the formatC
# solution.
scientific(numb, digits = 3)

## [1] "5.00e-02" "5.67e-02" "2.70e-08"

Note, digits is set to 3, not 2 as is the case for formatC