我编写了该cumsum
函数的一个变体,在添加当前值之前,我将先前的总和乘以衰减因子:
decay <- function(x, decay=0.5){
for (i in 2:length(x)){
x[i] <- x[i] + decay*x[(i-1)]
}
return(x)
}
这是一个演示,使用二进制变量使效果清晰:
set.seed(42)
Events <- sample(0:1, 50, replace=TRUE, prob=c(.7, .3))
plot(decay(Events), type='l')
points(Events)
编译这个函数会加快很多速度:
#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
但我怀疑矢量化会进一步改善它。有任何想法吗?