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

replace NA's with 0, and Non NA's with a different value

I have a dataframe like this:

my_df <- data.frame(
    ID = c(2, 4, 6, 8, 10, 12, 14, 16, 18), 
    b2 = c(NA, 4, 6, 2, NA, 6, 1, 1, NA))

and, I want to replace all NA’s with ‘0’, and every other values (Non-NA’s) with ‘1’, and place them in a new column (b4)

I can replace only NA’s with 0 using this:

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

my_df2 <- my_df %>%
    mutate(b3 = replace(b2,is.na(b2),0))

I would have thought I can use below step to then replace other values (Non-NA’s) with ‘1’:

my_df3 <- my_df2 %>% mutate(b4=ifelse(b3=="NA","0","1"))

This however, does not work the way I anticipated. Perhaps how to get through this in one go.
Any advice with this please?

>Solution :

You are not using NA properly here — you are treating it like a character variable in x=="NA" – with NA values, standard practice is to use is.na(), not x==NA. Try:

my_df$b3 <- ifelse(is.na(my_df$b2), 0, 1)
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