I have a very simple problem that’s driving me crazy!! I’m trying to conditionally replace values with NA in R. Here’s what I’ve tried so far using dplyr package.
First try
want = as.data.frame(
have %>%
mutate(gender = replace(gender, gender == "I Do Not Wish to Disclose", NA))
)
Second try
want = as.data.frame(
have %>%
mutate(gender = ifelse(gender == "I Do Not Wish to Disclose", NA, gender))
)
The first one gives me an error (god knows why?!!) and the second one runs without an error but turns Female -> 1, Male -> 3 and NA (I Do Not Wish to Disclose) -> 2…
Could someone please give me a hand with this?
This is driving me crazy…
Thanks,
Brian
>Solution :
It is case where the column is factor. Convert to character and it should work
library(dplyr)
have %>%
mutate(gender = as.character(gender),
gender = replace(gender, gender == "I Do Not Wish to Disclose", NA))
The change in values in gender is when it gets coerced to its integer storage values
as.integer(factor(c("Male", "Female", "Male")))