Controlling number of decimal digits in print output in R

前端 未结 3 809
说谎
说谎 2020-11-22 08:59

There is an option in R to get control over digit display. For example:

options(digits=10)

is supposed to give the calculation results in 1

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 09:36

    One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

    For example, if you have a vector as elements and would like to get sum of it

    elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
    sum(elements)
    ## -876.5432
    

    Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

    Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

    decimal_length <- 5
    formatC(sum(elements), format = "f", digits = decimal_length)
    ## -876.54321
    

    We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

提交回复
热议问题