R:获取元素的索引以排序向量向量、索引、元素

2023-09-11 06:26:20 作者:不懂挽留@

我有一个排序的载体,让我们说

I have a sorted vector, let's say

v <- c(1, 1, 2, 3, 5, 8, 13, 21, 34) 

现在我想找到该指数一大于二的例子中,第一个元素的 A&LT; - 15

Now I want to find the index i of the first element which is bigger than for example a <- 15.

我可以做类似 I&LT; - 这(V&GT;一个)[1]

不过,我想利用这个事实,即 v 的排序,我不认为问津。

But I want to exploit the fact that v is sorted, which I don't think which cares about.

我可以写我和递归划分间隔成两半,并在这些局部区间搜索...

I could write it myself and divide the interval recursively in halves and search in those partial intervals...

有没有内置的解决方案?像往常一样,主要问题是速度和我自己的职能将是肯定要慢。

Is there any built-in solution? As usual the main issue is speed and my own function would be slower surely.

感谢你。

推荐答案

有关速度馋嘴

a <- 10
v <- sort(runif(1e7,0,1000));
Rcpp::cppFunction('int min_index(NumericVector v, double a) {
                  NumericVector::iterator low=std::lower_bound (v.begin(), v.end(), a);
                  return (low - v.begin());
                  }')
microbenchmark::microbenchmark(which(v > a)[1], min_index(v, a), unit="relative")

#Unit: relative
#            expr      min       lq     mean   median      uq      max neval
#which(v > a)[1] 61299.15 67211.58 14346.42 8797.526 8683.39 11163.27   100
#min_index(v, a)     1.00     1.00     1.00    1.000    1.00     1.00   100