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:
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)