I have a character variable that has some values that I want replaced by NA (e.g. "N/A"; "NA" entered as text, not R's NA type; other text responses.) The values I don't want replaced by NA contain number strings, so I tried using a regular expression to select the non-number strings to replace with NA.
I'm able to filter for the non-number cases using the following, or the number string cases if I remove the "!". I'm been unable to figure out how to use mutate() with if_else() and str_detect() or na_if() with str_detect() to replace these cases. I've only been able to replace cases if I specify them exactly with na_if().
library(dplyr)
library(stringr)
df <- data.frame(var1 = c("84950", "NA", "N/A", "84596/03456", "55555", NA),
var2 = rep("10000", 6))
df %>%
filter(!str_detect(var1, "[:digit:]"))
This doesn't work.
df %>%
mutate(var1 = if_else(str_detect(var1, "[:digit:]"), var1, NA))
This doesn't work, leaves all the cases as is.
df %>%
mutate(var1 = na_if(var1, !str_detect(var1, "[:digit:]")))
This works to replace this particular value "N/A"
df %>%
mutate(var1 = na_if(var1, "N/A"))