【问题标题】:Finding which element of a vector is between two values in R查找向量的哪个元素位于 R 中的两个值之间
【发布时间】:2013-12-23 23:55:10
【问题描述】:

我有两个向量 xy。我想找出x 的哪些元素位于向量y 的两个元素之间。我如何在 R 中做到这一点?

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
numeric(0)

结果应该是这样的:

res = c(2.1, 5.3, 6.7)

【问题讨论】:

  • 未来的读者可能也会对findInterval 感兴趣,这不是这里所需要的,但它是另一种查找数字介于哪两个值之间的工具。
  • 另见this related question 以及this question 中的&amp;&amp;&amp; 的更多信息。

标签: r vector


【解决方案1】:

您正在寻找 &,而不是 &&:

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

编辑解释。这是来自?'&amp;' 的文字。

& 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. 

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

【讨论】:

    【解决方案2】:

    between 包含两个方便的函数,包含在 dplyrdata.table 包中

    在 {dplyr} 之间

    这是 x >= left & x

    在 {data.table} 之间

    between 等价于 x >= lower & x lower & y

    返回所需的值

    x[between(x, min(y), max(y))]
    

    使用 findInterval 的另一个选项

    x[findInterval(x,y)==1L]
    

    findInterval 使用作者的原始向量似乎有轻微(微秒)的速度优势

    Unit: microseconds
    
                   expr    min     lq     mean  median      uq     max neval
    dplyr::between      14.078 14.839 20.37472 18.6435 20.5455  60.876   100
    data.table::between 58.593 61.637 73.26434 68.2950 78.3780 160.560   100
    findInterval         3.805  4.566  6.52944  5.7070  6.6585  35.385   100
    

    用大向量更新

    x <- runif(1e8, 0, 10)
    y <- c(1, 7)
    

    结果显示 data.table 具有较大的矢量优势,但实际上它们足够接近,我可以使用您加载的任何包

    Unit: seconds
    
                  expr         min       lq     mean   median       uq      max neval
    dplyr::between        1.879269 1.926350 1.969953 1.947727 1.995571 2.509277   100
    data.table::between   1.064609 1.118584 1.166563 1.146663 1.202884 1.800333   100
    findInterval          2.207620 2.273050 2.337737 2.334711 2.393277 2.763117   100
    x>=min(y) & x<=max(y) 2.350481 2.429235 2.496715 2.486349 2.542527 2.921387   100
    

    【讨论】:

    • @Frank 基准已更新为长度为 1e8 的向量。大向量的结果有利于 data.table,但可能与您已经使用的数据包一致。
    【解决方案3】:

    如果y 有两个以上的元素,它可以派上用场:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 2017-07-18
      • 2017-04-29
      • 1970-01-01
      • 2014-08-26
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多