`%in%` 和 `==` 有什么区别? [英] What is the difference between `%in%` and `==`?
问题描述
df <- structure(list(x = 1:10, time = c(0.5, 0.5, 1, 2, 3, 0.5, 0.5,
1, 2, 3)), .Names = c("x", "time"), row.names = c(NA, -10L), class = "data.frame")
df[df$time %in% c(0.5, 3), ]
## x time
## 1 1 0.5
## 2 2 0.5
## 5 5 3.0
## 6 6 0.5
## 7 7 0.5
## 10 10 3.0
df[df$time == c(0.5, 3), ]
## x time
## 1 1 0.5
## 7 7 0.5
## 10 10 3.0
这里的 %in%
和 ==
有什么区别?
What is the difference between %in%
and ==
here?
推荐答案
问题在于向量回收.
您的第一行完全符合您的预期.它检查 df$time
的哪些元素在 c(0.5, 3)
中并返回值.
Your first line does exactly what you'd expect. It checks what elements of df$time
are in c(0.5, 3)
and returns the values which are.
你的第二行更棘手.它实际上相当于
Your second line is trickier. It's actually equivalent to
df[df$time == rep(c(0.5,3), length.out=nrow(df)),]
为了看到这一点,让我们看看如果使用向量 rep(0.5, 10)
会发生什么:
To see this, let's see what happens if use a vector rep(0.5, 10)
:
rep(0.5, 10) == c(0.5, 3)
[1] TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE
看看它如何返回每个奇数.本质上它是将 0.5 匹配到向量 c(0.5, 3, 0.5, 3, 0.5...)
See how it returns every odd value. Essentially it's matching 0.5 to the vector c(0.5, 3, 0.5, 3, 0.5...)
您可以通过这种方式操纵向量以不产生匹配项.取向量:rep(c(3, 0.5), 5)
:
You can manipulate a vector to produce no matches this way. Take the vector: rep(c(3, 0.5), 5)
:
rep(c(3, 0.5), 5) == c(0.5, 3)
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
它们都是FALSE
;您将每 0.5 与 3 匹配,反之亦然.
They're all FALSE
; you are matching every 0.5 with 3 and vice versa.
这篇关于`%in%` 和 `==` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!