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

前端 未结 2 1193
一生所求
一生所求 2020-12-08 19:13

I would like to have consistent output for a particular R script. In this case, I would like all numeric output to be in scientific notation with exactly two decimal places.

相关标签:
2条回答
  • 2020-12-08 19:18

    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

    0 讨论(0)
  • 2020-12-08 19:30

    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"
    
    0 讨论(0)
提交回复
热议问题