Recode/replace variables conditionally with R dyplyr?

旧巷老猫 提交于 2020-06-09 04:06:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!