rsignificant-digits

How do I customize R code for significant digits greater than 999?


I have been using this R code to give me 3 significant digits for a large dataset. It works beautifully, except when I have large error results that are greater than 999. Well, the code is still working correctly, but I want to modify it for results 1000 or higher, I want to see all numbers (except decimal points). For example, if my result is 21562.34, what I want to see is 21562. The code is currently giving me 21600 (which is correct) but how to I modify it to what I'm asking? Thank you!

sig <- function(x, dig = 3) {signif(x * 10^dig, dig)/ 10^dig}

Solution

  • We can use ifelse() to switch between the two behaviors you want:

    ifelse(abs(x) >= 1000, round(x), sig(x, dig = 3))
    
    ## or maybe in a function like this:
    sig_round = function(x, dig = 3) {
      ifelse(abs(x) >= 10^dig, round(x), sig(x, dig = dig))
    }