Search code examples
rdecimalsignificant-digits

finding the number of significant digits versus digits after decimal in r


I would like to find the number of significant digits in a vector of numbers that can have very different scales.

For example, the number 1000 has 1 digit; the number 100 also has 1. The number 1300 has 2.

This is not to be confused with the number of digits after decimal, that in both cases is equal to 0.


Solution

  • This function will convert each value in the vector to a character value, remove all leading zeros, trailing zeros, and decimal places, and count the number of characters remaining. It's performance appears to be comparable to phiver's answer.

    sigfigs <- function(x){
      orig_scipen <- getOption("scipen")
      options(scipen = 999)
      on.exit(options(scipen = orig_scipen))
    
      x <- as.character(x)
      x <- sub("\\.", "", x)
      x <- gsub("(^0+|0+$)", "", x)
      nchar(x)
    }
    
    x <- c(1000,100,1300, 1200.1, 12345.67, 12345.670)
    
    sigfigs(x)
    

    A note of caution:

    This function returns the number of digits that are neither leading nor trailing zeros. This is not exactly the same thing as the number of significant digits. while leading zeros are never significant, trailing zeros may or may not be significant--deciding if they are requires some knowledge about the precision of the measurement. I recommend reading the Wikipedia article on "Significant Figures" for more detail.