gpt4 book ai didi

r - 向量化函数 : cumsum with a decay parameter

转载 作者:行者123 更新时间:2023-12-04 05:26:03 27 4
gpt4 key购买 nike

我写了 cumsum 的变体函数,在添加当前值之前,我将先前的总和乘以衰减因子:

decay <- function(x, decay=0.5){
for (i in 2:length(x)){
x[i] <- x[i] + decay*x[(i-1)]
}
return(x)
}

下面是一个demo,使用一个二元变量来说明效果:
set.seed(42)
Events <- sample(0:1, 50, replace=TRUE, prob=c(.7, .3))
plot(decay(Events), type='l')
points(Events)

Rplot

编译这个函数会大大加快它的速度:
#Benchmark
library(compiler)
library(rbenchmark)
cumsum_decayCOMP <- cmpfun(cumsum_decay)
Events <- sample(0:1, 10000, replace=TRUE, prob=c(.7, .3))
benchmark(replications=rep(100, 1),
cumsum_decay(Events),
cumsum_decayCOMP(Events),
columns=c('test', 'elapsed', 'replications', 'relative'))

test elapsed replications relative
1 cumsum_decay(Events) 3.28 100 6.979
2 cumsum_decayCOMP(Events) 0.47 100 1.000

但我怀疑矢量化会进一步改善它。有什么想法吗?

最佳答案

试试 filter功能:

filter.decay <- function(x, decay=0.5) filter(x, decay, method = "recursive")

它非常快:
#                       test elapsed replications relative
# 1 cumsum_decay(Events) 4.83 100 19.32
# 2 cumsum_decayCOMP(Events) 1.00 100 4.00
# 3 filter.decay(Events) 0.25 100 1.00

关于r - 向量化函数 : cumsum with a decay parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201206/

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