【发布时间】:2022-02-11 18:57:27
【问题描述】:
我经常使用 dplyr 来处理数据,但我从未弄清楚使用 filter(df, variable == c(value1, value2) 时的 dplyr 过滤器行为
我们以iris 数据集为例。
library(dplyr)
data(iris)
# I want to filter by Species 'setosa' and 'versicolor'
# Solution 1
filter1 <- filter(iris, Species == 'setosa' | Species == 'versicolor')
nrow(filter1)
[1] 100 # expected result
# Solution 2
filter2 <- filter(iris, Species %in% c('setosa', 'versicolor'))
nrow(filter2)
[1] 100 # expected result
filter1 == filter2 # both solutions return the exact same result
#Solution 3
filter3 <- filter(iris, Species == c('setosa', 'versicolor'))
nrow(filter3)
[1] 50 # unexpected result
unique(filter3$Species)
[1] setosa versicolor
Levels: setosa versicolor virginica
尽管Solution 3 正在过滤预期的物种,如unique(filter3$Species) 所示,但它只返回一半的出现(50 与Solution 1 和Solution2 中的100 相比)。对于Solution 3 中实际发生的情况,我将不胜感激。
【问题讨论】:
-
它正在回收
c('setosa', 'versicolor')以匹配Species的长度,因此它在 100 行中只有 50% 的时间与Species匹配。试试c("a", "b", "a", "b") == c("a", "b")和c("a", "b", "b", "a") == c("a", "b")看看有什么区别。 -
你可以在这篇文章中看到详细信息:What is the difference between `%in%` and `==`?
-
我明白了,谢谢您的评论!根据我的具体示例,在执行
iris$Species == c('setosa', 'versicolor')时,这种行为变得非常清楚!