【发布时间】:2021-02-21 16:29:05
【问题描述】:
我有一个包含许多变量的数据集,其中两个称为“动物”和“植物”。两个变量都是因子,并且都是二元的,即它们要么是文本值,要么是 NA。
例如:
animal <- c(NA, NA, "cat", "cat", NA)
plant <- c("ivy", NA, "ivy", NA, NA)
value <- c(1:5)
df <- data.frame(animal, plant, value)
> df
animal plant value
1 <NA> ivy 1
2 <NA> <NA> 2
3 cat ivy 3
4 cat <NA> 4
5 <NA> <NA> 5
当植物的值为“ivy”,动物的值为“cat”时, 我想将植物的值更改为 NA(即,这两件事不能为真,动物值优先。我的其他变量没有任何变化
我尝试了以下方法,但收到错误消息:
df <- df %>% if (isTRUE(animal == "cat")) {plant==NA}
Error in if (.) isTRUE(animal == "cat") else { :
argument is not interpretable as logical
In addition: Warning message:
In if (.) isTRUE(animal == "cat") else { :
the condition has length > 1 and only the first element will be used
我的目标输出是:
> df
animal plant value
1 <NA> ivy 1
2 <NA> <NA> 2
3 cat <NA> 3
4 cat <NA> 4
5 <NA> <NA> 5
我非常感谢任何帮助。我确信有一种非常简单的方法可以做到这一点,也许我只见树木不见森林。
【问题讨论】:
标签: r dataframe if-statement na