查找向量的哪个元素在 R 中的两个值之间 [英] Finding which element of a vector is between two values in R

查看:29
本文介绍了查找向量的哪个元素在 R 中的两个值之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个向量 xy.我想找出 x 的哪些元素在向量 y 的两个元素之间.我怎样才能在 R 中做到这一点?

I have two vectors x and y. I would like to find which elements of x are between the two elements of vector y. How can I do it in R?

x = c( .2, .4, 2.1, 5.3, 6.7, 10.5)
y = c( 1, 7)

我写了下面的代码,但它没有给我正确的结果.

I have written the following code, but it does not give me the correct result.

> x = x[ x >= y[1] && x <= y[2]]
> x
numeric(0)

结果应该是这样的:

res = c(2.1, 5.3, 6.7)

推荐答案

您要找的是 & 而不是 &&:

You are looking for &, not &&:

x = c( .2, .4, 2.1, 5.3, 6.7, 10.5)
y = c( 1, 7)
x = x[ x >= y[1] & x <= y[2]]
x
# [1] 2.1 5.3 6.7

编辑解释.这是来自 ?'&' 的文本.

Edited to explain. Here's the text from ?'&' .

& and && indicate logical AND and | and || indicate logical OR. 
The shorter form performs elementwise comparisons in much the same way as arithmetic operators. 
The longer form evaluates left to right examining only the first element of each vector. 
Evaluation proceeds only until the result is determined. 

因此,当您使用 && 时,它为 x 的第一个元素返回 FALSE 并终止.

So when you used && , it returned FALSE for the first element of your x and terminated.

这篇关于查找向量的哪个元素在 R 中的两个值之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆