Using R, I have data that looks like:
A, B
= =====
x," 120"
y," 2300"
z,"1.2 M"
x," 4500"
x," 42 M"
This was constructed using:
A <- c("x","y","z","x","x")
B <- c(" 120", " 2300", "1.2 M", " 4500", " 42 M")
data <- data.frame(A, B)
I want to convert the second column to a valid number (the 'M' signifies millions). What I have is:
df <- data %>%
mutate( B = ifelse( grepl("^ *[0-9]+$", .$B),
as.numeric(.$B),
1000000 * as.numeric(sub(" *([0-9]+) M", "\\1", .$B))))
ie. it looks for a field with an 'M', and if found does as.numeric on the sustricg and multiplies by 1000000.
This works fine, EXCEPT I get a warning:
Warning messages:
1: Problem with `mutate()` input `B`.
i NAs introduced by coercion
i Input `B` is `ifelse(...)`.
2: In ifelse(grepl("^ *[0-9]+$", .$B), as.numeric(.$B), 1e+06 * :
NAs introduced by coercion
But when I inspect the data using df %>% filter(is.na(B)), there are no NAs
I don't want to disable the warning entirely, but I do want to avoid it when it's "invalid".
Any suggestions? Ami I missing something?