From a character column in a tibble, I'm trying to extract numbers and convert to numeric type using ifelse()
to apply as.numeric()
on values that do not contain letters (or "+").
While this example works, it returns a warning message:
library(dplyr)
tibble(a = c("0", "0.1", "abc")) %>%
mutate(b = ifelse(!grepl("[a-zA-Z\\+]+", a), as.numeric(a), NA))
# A tibble: 3 × 2
a b
<chr> <dbl>
1 0 0
2 0.1 0.1
3 abc NA
Warning message:
Problem while computing `b = ifelse(grepl("[a-zA-Z\\+]+", a), NA, as.numeric(a))`.
ℹ NAs introduced by coercion
Please help me understand why my script is still trying to convert the character value to numeric, and how I can fix this.