How to recode 0 values of a variable to NA based on a condition from another variable

I have a dataset where I have a variable called screen12m which is a 1,0 binary variable.

I want to change some of these zeros to NAs based on a condition from another variable which is called offset. So if offset variable value is < 1, I would like these zeros to be recoded into nas.

I tried:

data6 <- data5 %>%
mutate(screen12m = recode_if(screen12m, offset < 1 , "0" = NA))

However that doesn't work.

Any ideas/suggestions?

Thanks in advance!

See the FAQ: How to do a minimal reproducible example reprex for beginners; having to reverse engineering data required to test a solution deters answers.

Something like this may work:

data6 <- data5 %>% mutate(screen12m = ifelse(offset  < 1, NA,screen12m))
1 Like

Thank you! I tried this command, however it returns NAs for the values of 1 of the screen12m variable as well.

I am trying to condition it only for the 0s.

So you want offset to be < 1 AND screen12m ==0

data6 <- data5 %>% mutate(screen12m = ifelse((offset < 1 & screen12m ==0), NA,screen12m)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.