Getting a vector of n-sized digits - only from a numeric value in R

I am trying to write a function that returns a vector of numbers representing the n decimal digits of the provided x number. And this is the code I have written so far:

decdig <- function(x, n){
   stopifnot(is.numeric(x))
   stopifnot(is.integer(n))
   head ( lapply(strsplit( as.character(x) , ""), as.numeric) , n)
}

      

So the instruction:

decdig (pi, 10L)

Return:

[[1]]
 [1]  3 NA  1  4  1  5  9  2  6  5  3  5  8  9  7  9

      

But it should be:

3 1 4 1 5 9 2 6 5 3

      

This means it must produce a numeric vector without rounding.

I'm having a problem getting rid of the NA values ​​sitting there because of the comma. I try to make it as elegant as possible without using flow control mechanisms.

Any ideas are appreciated.

+3


source to share


1 answer


Here's one way to do it:

decdig <- function(x, n) {
  stopifnot(is.numeric(x))
  stopifnot(is.integer(n))
  z <- sub('\\D', '', 
           sprintf(paste0('%.', n - nchar(abs(floor(x))) + 2, 'f'), x))
  head((strsplit(z, '')[[1]]), n)
}

decdig(pi, 10L)
# [1] 3 1 4 1 5 9 2 6 5 3

      



We calculate the number of decimal places needed (if any) by subtracting the number of leading digits from n

, then passing that to sprtinf

to force it x

into a character with that many decimal places. We then output non-digit characters (which should only include ,

or .

, depending on the language). Then we separate each character and force them to numeric

.

+1


source







All Articles