Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditionally replace values with NA in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading