Search code examples
rdataframeformat

Trailing Zeros and other problems with sigifig formatting in R


I need a consult on getting a more robust method for formatting a string of numbers (and potential NA or other non-numeric entry) into a neat sig fig format. I want to know if there is an elegant way of handling small numbers say 0.00435 and larger numbers like 23345, into a neat output format where big numbers get a comma and small nubmers have the the right amount of sig figs.

below is my attempt

    num_of_sig_figs = 3
    a = c(0.3459215,0.6227059,7.409618,462.3468600,9.090436,6293.4189000)
      
    a_sigfig <- format(round(a,num_of_sig_figs-(1+as.integer(log10(abs(a))))), big.mark=",")
    a_sigfig

    # "    0.35" "    0.62" "    7.41" "      NA" "  462.00" "    9.09" "6,290.00"

I am getting trailing zeros on my larger numbers with the correct amount of sigfigs but my smaller number are short a sigfig. IS there a way to do this without a several cases?

Also it would be a nice to have to not have to loose the numeric format.

Please note that the difference between this and previously posed questions is the inclusion of the "," for big numbers AND staying numeric in format for subsequent processing if needed


Solution

  • Req 1

    a more robust method for formatting a string of numbers (and potential NA or other non-numeric entry) into a neat sig fig format

    Req 2

    Also it would be a nice to have to not have to loose the numeric format.

    The bigmark = "," makes it difficult to meet Req 2. Without it, you could do something similar to this

    sigfig <- function(x, dig = 3){
      x <- suppressWarnings(as.numeric(x))
      suppressWarnings(as.numeric(formatC(signif(x,digits=dig), digits=dig, format="fg", flag="#")))
    }
    
    sigfig(c(0.3459215,NA,"test",462.3468600,9.090436,6293.4189000))
    
    [1]    0.346       NA       NA  462.000    9.090 6290.000
    

    Meeting Req 1, but loosing the numeric type

    sigfig_char <- function(x, dig = 3){
      x <- suppressWarnings(as.numeric(x))
      gsub("\\.$", "", formatC(signif(x,digits=dig), digits=dig, format="fg", flag="#", big.mark = ","))
    }
    
    sigfig_char(c(0.3459215,NA,"test",462.3468600,9.090436,6293.4189000))
    [1] "0.346" "  NA"  "  NA"  "462"   "9.09"  "6,290"