首页 > 解决方案 > 改变 ifelse 以替换 r 中的值

问题描述

我有一个如下所示的数据框:

Word     Value1   Value2

Apple    True     True
Chair    True     False
nonWord  False    False
Hat      False    True
...      ...

我正在尝试将 nonWords 的所有值更改为NA's.

data %>%
  mutate(Value1 = ifelse(Word == "nonWord", NA, Value1)) %>%
  mutate(Value2 = ifelse(Word == "nonWord", NA, Value2))

但是,这似乎不起作用,因为我的价值观没有被NA's. 有谁知道我做错了什么?

期望的输出:

Word     Value1   Value2

Apple    True     True
Chair    True     False
nonWord  NA       NA
Hat      False    True
...      ...

标签: rdata-wrangling

解决方案


最好使用replace()frombase R而不是ifelse()这些情况:

library(dplyr)

df %>%
  mutate(Value1 = replace(Value1, Word == "nonWord", NA),
         Value2 = replace(Value2, Word == "nonWord", NA))

#>      Word Value1 Value2
#> 1   Apple   True   True
#> 2   Chair   True  False
#> 3 nonWord   <NA>   <NA>
#> 4     Hat  False   True

如果您确定要替换的所有列都命名为“Value...”,则可以利用mutate_at()from dplyr

library(dplyr)

df %>%
  mutate_at(vars(starts_with("Value")), ~ replace(., Word == "nonWord", NA))

#>      Word Value1 Value2
#> 1   Apple   True   True
#> 2   Chair   True  False
#> 3 nonWord   <NA>   <NA>
#> 4     Hat  False   True

数据

df <- structure(list(Word = c("Apple", "Chair", "nonWord", "Hat"), 
    Value1 = c("True", "True", "False", "False"), Value2 = c("True", 
    "False", "False", "True")), class = "data.frame",
    row.names = c(NA, -4L))

推荐阅读