Search code examples
rwolfram-mathematicasubstrlead

Get the first non zero digit in R similar to Mathematica


In mathematica we have RealDigits that can identify the first non-zero number for both numbers with decimal point and integer values. See below as an example:

RealDigits[ 0.00318, 10, 1]
{{3},-2}
RealDigits[ 419, 10, 1]
{{4},-2}

In the above example the function identifies, 3 and 4 respectively for 0.00318 and 419.

Is there a similar function in R?


Solution

  • You could do:

    x <- c(0.0000318, 419)
    
    as.numeric(substr(formatC(x, format = 'e'), 1, 1))
    # [1] 3 4