返回true/fals
我正在寻找一种有效的方法来创建一个布尔向量,该矢量返回true
如果一个或多个指定变量的数字,例如c(1,2, 3)
在另一个向量中,例如c(4,5,6,1)
。
在此示例中,寻求的输出将是true
,因为元素1
都存在于两个向量中。
据我所知,%仅允许一次检查一个变量并使用|
操作员在这种情况下效率低下为了。使用InterSect()
返回逻辑(0)
而不是false
和sum(c(1,2,3)== c(4,5,6,1))> 1
返回false
,因为共同元素不在同一位置。
I'm looking for an efficient way to create a boolean vector which returns TRUE
if one or more of a number of specified variables e.g. c(1,2,3)
are in another vector e.g. c(4,5,6,1)
.
In this example the output sought would be TRUE
as the element 1
is present in both vectors.
As far as I know %in%
only permits checking one variable at a time and using the |
operator is inefficient in this case given the number of potential variables I need to check for. Using intersect()
returns logical(0)
rather than FALSE
, and sum(c(1,2,3) == c(4,5,6,1)) > 1
returns FALSE
as the common elements are not in the same position.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
更新: @m-所说的,如果没有匹配,它还给了True!这是避免这种情况的方法:
第一个答案:
另一个否定<代码>全部:
Update: As commented by @M-- in case of no matches it gives back TRUE! Here is how to avoid this:
First answer:
One more with negating
all
:另一个选项:
输出:
Another option:
Output:
您可以使用
任何
:You can use
any
:这是使用
is.Element
with的另一个选项:
或其他选项是使用
MATD> MATCH
与任何(尽管将会可能效率较低):Here's another option using
is.element
withany
:Or another option is to use
match
withany
(though would probably be less efficient):使用
任何
是最有效的方法,但是仅提供另一种解决方案,这里是使用sum
:或我们可以使用
length
:Using
any
is the most efficient way, but just to offer another solution, here's one usingsum
:Or we can use
length
:还有一个
不是很好的选择:
One more
not great option: