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

Mik*_*ouk 1 sorting algorithm performance r

我有一个排序的矢量,比方说

v <- c(1, 1, 2, 3, 5, 8, 13, 21, 34) 
Run Code Online (Sandbox Code Playgroud)

现在我想找到i比例子大的第一个元素的索引a <- 15.

我可以做点什么i <- which(v > a)[1].

但我想利用v已排序的事实,我不认为这是which关心的事实.

我可以自己编写它并将这个间隔递归地分成两半并在那些部分间隔中搜索...

有没有内置的解决方案?像往常一样,主要问题是速度,我自己的功能肯定会慢一些.

谢谢.

Kha*_*haa 5

对于速度馋嘴

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
Run Code Online (Sandbox Code Playgroud)