问题
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 has no value greater than 0 (which is coded as NA), then the value in var2 should remain as it is. The line of code below codes everything in var2 to NA and does not keep the values in var2 if var1 is NA. I have also tried to use na_if() and coalesce() with not much success. Any possible fix to this?
df <- df %>%
mutate(var2 = if_else(var1 > 0, NA, var2 = TRUE ))
回答1:
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))
来源:https://stackoverflow.com/questions/59827756/recode-replace-variables-conditionally-with-r-dyplyr