R Displays Numbers in Scientific Notation

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

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"

How to prevent scientific notation in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation (?options):

‘scipen’: integer.  A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive
values bias towards fixed and negative towards scientific
notation: fixed notation will be preferred unless it is more
than ‘scipen’ digits wider.

So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999:

options(scipen=999)

R displays numbers in scientific notation

You can do:

format(functionResult, scientific=FALSE);

or:

as.integer(functionResult);

Force R not to use exponential notation (e.g. e+10)?

This is a bit of a grey area. You need to recall that R will always invoke a print method, and these print methods listen to some options. Including 'scipen' -- a penalty for scientific display. From help(options):

‘scipen’: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive
values bias towards fixed and negative towards scientific
notation: fixed notation will be preferred unless it is more
than ‘scipen’ digits wider.

Example:

R> ran2 <- c(1.810032e+09, 4) 
R> options("scipen"=-100, "digits"=4)
R> ran2
[1] 1.81e+09 4.00e+00
R> options("scipen"=100, "digits"=4)
R> ran2
[1] 1810032000 4

That said, I still find it fudgeworthy. The most direct way is to use sprintf() with explicit width e.g. sprintf("%.5f", ran2).

Using format() in R to convert numeric value to scientific notation after rounding

I think rounded_vals might have been stored as character values. Try converting them to numbers using as.numeric() and then put it into the format() function.

Control the number of decimals in scientific notation

From my comment:

Let

x <- c(0, 1.23, 0.0000123)

and try

sprintf("%.3e", x)
[1] "0.000e+00" "1.230e+00" "1.230e-05"

If you don't want the quotes and the [1] to be displayed then do this

cat(sprintf("%.3e", x),"\n")
0.000e+00 1.230e+00 1.230e-05


Related Topics



Leave a reply



Submit