gpt4 book ai didi

r - 如何为向量的每个元素找到前 n 个值的最小值?

转载 作者:行者123 更新时间:2023-12-01 08:28:31 25 4
gpt4 key购买 nike

到目前为止,我在这样的函数中使用循环:

# x is a vector of numbers
# [1] 0 1 -1 -5 100 20 15

function(x,n){

results <- numeric(length(x)-n+1)

for(i in 1:(length(x)+1-n)){
results[i] <- min(x[i:(i+n-1)])
}

return(results)
}

## outputs this for x and n = 3
# [1] -1 -5 -5 -5 15

我想知道是否有可能不需要循环的更有效的解决方案。

编辑::

我在具有 6019 个观察值的向量上运行了两个带有微基准的解决方案。当我有时间(/弄清楚如何)时,我可以尝试具有各种观察大小的每个解决方案,以查看每个解决方案的有效性。但现在:

Rcpp 解决方案:

> microbenchmark(nmin(x,3))
Unit: microseconds
expr min lq mean median uq max neval
nmin(x, 3) 53.885 54.313 57.01953 54.7405 56.023 93.656 100

caTools 解决方案:

microbenchmark(runmin(x[[1]],3,endrule='trim'))
Unit: microseconds
expr min lq mean median uq max neval
runmin(x[[1]], 3, endrule = "trim") 231.788 241.8385 262.6348 249.964 262.5795 833.923 100

动物园解决方案:

> microbenchmark(rollapply(x[[1]],3,min))
Unit: milliseconds
expr min lq mean median uq max neval
rollapply(x[[1]], 3, min) 42.2123 47.2926 50.40772 50.33941 52.50033 98.46828 100

我的解决方案:

  > microbenchmark(nDayLow(x[[1]],3))
Unit: milliseconds
expr min lq mean median uq max neval
nDayLow(x[[1]], 3) 13.64597 14.51581 15.67343 15.33006 15.71324 63.68687 100

最佳答案

听起来是 Rcpp 的一个很好的用例。复制粘贴它并像任何其他功能一样使用它。我相信有很多方法可以让这变得更加高效(我的意思是我不是特别擅长 c++,我很确定你可以在这里使用一些不错的 STL):

require(Rcpp)
Rcpp::cppFunction( 'IntegerVector nmin( NumericVector x , int n ){
int N = x.size();
IntegerVector out(N-n+1);
for( int i = 0; i < out.size(); ++i){
int nmin=x[i];
for( int j = 0; j < n; ++j){
int tmp=x[j+i];
if( tmp < nmin ){
nmin=tmp;
}
}
out[i]=nmin;
}
return out;
}')

nmin(x,3)
#[1] -1 -5 -5 -5 15
nmin(x,7)
#[1] -5

它比 runmin 快大约 30 倍:

print( microbenchmark(runmin(x,3,endrule='trim'),nmin(x,3),unit="relative") , digits = 1 )
#Unit: relative
# expr min lq median uq max neval
# runmin(x, 3, endrule = "trim") 55 41 36 34 19 100
# nmin(x, 3) 1 1 1 1 1 100

关于r - 如何为向量的每个元素找到前 n 个值的最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27014883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com