使用 %in% 或 == 条件的 R 子集.应该使用哪一种? [英] R subset with condition using %in% or ==. Which one should be used?
问题描述
通常,如果我想对某些值的数据帧条件进行子集化,我使用的变量是子集和 %in%:
Usually, if I want to subset a dataframe conditioning of some values a variable I'm using subset and %in%:
x <- data.frame(u=1:10,v=LETTERS[1:10])
x
subset(x, v %in% c("A","D"))
现在,我发现 == 也给出了相同的结果:
Now, I found out that also == gives the same result:
subset(x, v == c("A","D"))
我只是想知道它们是否相同,或者是否有理由偏爱一个.感谢您的帮助.
I'm just wondering if they are identically or if there is a reason to prefere one over the other. Thanks for help.
编辑(@MrFlick):这个问题与不同this here 询问如何不包含多个值:(!x %in% c('a','b'))
.我问为什么如果我使用 ==
或 %in%
会得到同样的结果.
Edit (@MrFlick): This question asks not the same as this here which asks how to not include several values: (!x %in% c('a','b'))
. I asked why I got the same if I use ==
or %in%
.
推荐答案
你应该使用第一个 %in%
因为你得到结果只是因为在示例数据集中,它是在顺序中A
、D
的回收.这里是比较
You should use the first one %in%
because you got the result only because in the example dataset, it was in the order of recycling of A
, D
. Here, it is comparing
rep(c("A", "D"), length.out= nrow(x))
# 1] "A" "D" "A" "D" "A" "D" "A" "D" "A" "D"
x$v==rep(c("A", "D"), length.out= nrow(x))# only because of coincidence
#[1] TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE
subset(x, v == c("D","A"))
#[1] u v
#<0 rows> (or 0-length row.names)
虽然在上面
x$v==rep(c("D", "A"), length.out= nrow(x))
#[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
而 %in%
有效
subset(x, v %in% c("D","A"))
# u v
#1 1 A
#4 4 D
这篇关于使用 %in% 或 == 条件的 R 子集.应该使用哪一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!