3

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
forecaster
  • 1,084
  • 1
  • 14
  • 35

2 Answers2

4

You could do:

x <- c(0.0000318, 419)

as.numeric(substr(formatC(x, format = 'e'), 1, 1))
# [1] 3 4
zx8754
  • 52,746
  • 12
  • 114
  • 209
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

This function will accept vector arguments as well as a depth parameter letting you define how many digits you want to have after the first significant one.

x <- c(0.00318, 0.000489, 895.12)
RealDigits <- function(x, depth=1) {
  y <- as.character(x)
  ysplit <- strsplit(y,"")
  ysplit <- strsplit(y,"")
  last0 <- lapply(ysplit, function(x) tail(which(x==0),1))
  last00 <- sapply(last0, function(x) if (length(x) ==0) 0 else x )
  res <- substr(y, last00+1, as.numeric(sapply(y, nchar)))
  return(substr(res, 0,depth))
}
RealDigits(x)
RealDigits(x, depth =2)

> RealDigits(x)
[1] "3" "4" "8"
> RealDigits(x, depth =2)
[1] "31" "48" "89"
gaut
  • 5,771
  • 1
  • 14
  • 45