Is there a way you could extract the 1st non-zero digit of a numeric value in R?
Example input:
123.01, 0.56, 0.078, 0.0092
Output:
1, 5, 7, 9
Is there a way you could extract the 1st non-zero digit of a numeric value in R?
Example input:
123.01, 0.56, 0.078, 0.0092
Output:
1, 5, 7, 9
This works with positive inputs:
firstdigit <- function(x){ floor(x / 10 ^ floor(log10(x))) }
firstdigit(c(123.01, 0.56, 0.078, 0.0092))
# 1 5 7 9
You can use sub() from base R:
x <- c("123.01", "0.56", "0.078", "0.0092", "-1.2", "-0.3", "-0.04", "100")
sub("[^1-9]*(.).*", "\\1", x)
or with gsub()
y <- gsub("[^1-9]", "", x)
substr(y, 1,1)
This last you can modify to find the second digit:
y <- gsub("[^1-9]", "", x)
substr(y, 2,2)
From the comments:
For this case the problem needs to be worded differently.
"Extract the second digit after leading zeros" or "extract the second significant figure".
y <- sub("^[^1-9]*", "", x)
y <- gsub("\\.", "", y)
substr(y, 2,2)
You can use regex to extract. Using the stringr package:
set.seed(1)
x <- c(123.01, 0.56, 0.078, 0.0092)
x
#> [1] 123.0100 0.5600 0.0780 0.0092
stringr::str_extract(as.character(x), "([1-9]{1})")
#> [1] "1" "5" "7" "9"
You can convert back to numeric as necessary.
We can use gsub to remove leading 0's, trimws to remove dot and 0 or more zeroes and then extract first character using substr.
x <- c(123.01, 0.56, 0.078, 0.0092)
substr(trimws(gsub('^0', '', x), "left", "\\.0*"), 1, 1)
#[1] "1" "5" "7" "9"