Extract first digit from each element of a numeric vector in R

Viewed 633

A little bit like here, I would like to extract the first digit from each element of a numeric vector, without having it to turn into a character vector and back.

d <- c(123, 2, 45)

Expected Output:

[1] 1 2 4

I tried different stuff with floor(), but without the desired result.

1 Answers

One numerical approach here would be to divide each input number by 10 raised to the floor of log base 10. This means that, for example, we divide an input of 123 by 100, to yield 1.23. Then, we take the floor of that to yield the first digit 1.

getFirstDigit <- function(x) {
    floor(x / (10 ^ floor(log10(x))))
}

d <- c(123, 2, 45)
getFirstDigit(d)

[1] 1 2 4

The more brute force way of doing this would be to cast the input vector to character, take the first character, and then cast back to a number. But, I doubt doing it that way would outperform what I have above.

Related