I am trying to use the following code to recode my variables conditionally so that the values in var 2 are replaced by NA if there is any value greater than 0 in var1. If var1 h
We don't need var2 = TRUE
, instead it should be var2
library(dplyr)
df %>%
mutate(var2 = ifelse(var1 > 0, NA, var2))
if_else
is type specific, so you need to have the correct NA
type matching the 'var2' type. Assuming it is numeric
:
df %>%
mutate(var2 = if_else(var1 > 0, NA_real_, var2))
But, this can be also done with :
df %>%
mutate(var2 = replace(var2, var1 > 0, NA))
Or with case_when
:
df %>%
mutate(var2 = case_when(var1 > 0 ~ NA_real_, TRUE ~ var2))