我有两个向量x和y.我想找出xvector的两个元素之间的哪些元素y.我怎么能在R?
x = c( .2, .4, 2.1, 5.3, 6.7, 10.5)
y = c( 1, 7)
Run Code Online (Sandbox Code Playgroud)
我写了以下代码,但它没有给我正确的结果.
> x = x[ x >= y[1] && x <= y[2]]
> x
numeric(0)
Run Code Online (Sandbox Code Playgroud)
结果应该是这样的:
res = c(2.1, 5.3, 6.7)
Run Code Online (Sandbox Code Playgroud)
您正在寻找&,而不是&&:
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
Run Code Online (Sandbox Code Playgroud)
编辑解释.这是来自的文字?'&'.
& 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.
Run Code Online (Sandbox Code Playgroud)
因此,当您使用时&&,它返回FALSE作为您的第一个元素x并终止.
和包中between包含两个方便的函数dplyrdata.table
{dplyr}之间
这是 x >= left & x <= right 的快捷方式,在 C++ 中为本地值有效实现,并为远程表转换为适当的 SQL。
{data.table}之间
当 incbounds=TRUE 时, between 等价于 x >=lower & x <= upper,或者当 incbounds=TRUE 时 x > lower & y < upper
返回所需的值
x[between(x, min(y), max(y))]
Run Code Online (Sandbox Code Playgroud)
使用 findInterval 的另一种选择
x[findInterval(x,y)==1L]
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
用大向量更新
x <- runif(1e8, 0, 10)
y <- c(1, 7)
Run Code Online (Sandbox Code Playgroud)
结果显示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
Run Code Online (Sandbox Code Playgroud)