R:获取元素的索引以排序向量 [英] R: Getting indices of elements in a sorted vector
本文介绍了R:获取元素的索引以排序向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个排序的载体,让我们说
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
这篇关于R:获取元素的索引以排序向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文