Recode/replace variables conditionally with R dyplyr?

前端 未结 1 1359
一个人的身影
一个人的身影 2021-01-25 17:26

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

相关标签:
1条回答
  • 2021-01-25 17:55

    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))
    
    0 讨论(0)
提交回复
热议问题