Search code examples
rvectorformatscientific-notation

R: Format Numbers in a Vector Individually


I have a series of 10 p-values in a column of a data frame:

df$p <- c(0.00000005, 0.000001, 0.0001, 0.001, 0.01, 0.05, 0.1, 0.2, 0.5, 1)

Since it's easier to read the larger p values in decimal, and the smaller ones in scientific notation, I want it formatted like this:

5e-8, 1e-6, 1e-4, 0.001, 0.01, 0.05, 0.1, 0.2, 0.5, 1

But no matter how I play with options(scipen=whatever) and format(df$p, scientific=whatever), R displays all the elements in the same manner (i.e. all in decimal, or all in scientific notation).

What I want is for R to apply the scientific penalty to each element of this vector individually, so they display as decimal or in SN depending on which saves more space.


Solution

  • Use the following option

    > p <- c(0.00000005, 0.000001, 0.0001, 0.001, 0.01, 0.05, 0.1, 0.2, 0.5, 1)
    > options(scipen = 999)
    > p
     [1] 0.00000005 0.00000100 0.00010000 0.00100000 0.01000000 0.05000000 0.10000000 0.20000000 0.50000000 1.00000000
    > options(scipen = 1)
    > p
     [1] 5e-08 1e-06 1e-04 1e-03 1e-02 5e-02 1e-01 2e-01 5e-01 1e+00
    

    Maybe you need to put options(scipen) in the beginning of your script. Or you can use

    > mapply(format, p)
     [1] "5e-08"  "1e-06"  "0.0001" "0.001"  "0.01"   "0.05"   "0.1"    "0.2"    "0.5"    "1"