是否可以对以下函数 ( f
) 进行矢量化?
我有一个向量x
,我想f
通过改变来最大化函数的输出值p
。
但是这个函数很慢,因为它无论如何都没有向量化,并且想知道是否有一个好的方法来做到这一点。这个想法是在未来将其并行化,并可能用于data.table
加速它
我的真实数据要大得多……所以我提供了一个模拟示例……
# My mock data
x <- data.frame(x=rep(c(rep(c(0.2,-0.2),4),0.2,0.2,-0.2,0.2),20))
# The function to optimise for
f <- function(p,x){
# Generate columns before filling
x$multiplier <- NA
x$cumulative <- NA
for(i in 1:nrow(x)){
# Going through each row systematically
if(i==1){
# If first row do a slightly different set of commands
x[i,'multiplier'] <- 1 * p
x[i,'cumulative'] <- (x[i,'multiplier'] * x[i,'x']) + 1
} else {
# For the rest of the rows carry out these commands
x[i,'multiplier'] <- x[i-1,'cumulative'] * p
x[i,'cumulative'] <- (x[i,'multiplier'] * x[i,'x']) + x[i-1,'cumulative']
}
}
# output the final row's output for the cumulative column
as.numeric(x[nrow(x),'cumulative'])
}
# Checking the function works by putting in a test value of p = 0.5
f(0.5,x)
# Now optimise the function between the interval of p between 0 and 1
optim.p <- optimise(f=f, interval=c(0,1),x, maximum=TRUE)
# Viewing the output of optim.p
optim.p