Is it possible to vectorise the following function, (f)?
I have a vector x for which I want to maximise the output value of the function f by altering p.
But the function is quite slow as it is not vectorised in anyway and was wondering if there was a good way to do so. The idea is to parallelise this in the future, and also potentially use data.table to speed it up
my real data is significantly larger...so I'm providing a mock example....
# 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