r - 改变 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
... ...
解决方案
最好使用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))
推荐阅读
- java - 编译失败:-source 7 中不支持 lambda 表达式
- php - 如何在 php 代码库中停止请求具有 504 超时响应的外部 API
- c# - 错误 System.NullReferenceException:“对象引用未设置为对象的实例。” 在集合视图中(再次)
- c# - System.IO.FileLoadException 如果在设置文件中使用俄语字母
- react-native - 如何在 React Navigation 中使用标题按钮导航到其他页面?
- javascript - 运行 React-DOM 的 JS onLoad
- java - 提取jar时spring boot运行JarLauncher
- javascript - 尝试在 Typescript 中执行时出现异步/等待问题,但在 Javascript 中有效
- sql-server - 规范化大写字符串,但保持括号中的内容相同
- html - Sizes 属性在图像中不起作用