Is it possible to vectorize / speed up the execution of a FOR loop that is using the previous iteration values ?
In the reproductive example below :
- the current production is computed from the current stock
- the current production updates the NEXT stock
- the next iteration used the updated stock to determine the current production, etc...
So I need to compute the stock at each iteration, in order to compute the production setpoint... Is it possible to avoid (slow) for loop ?
The current implementation takes about 45 seconds for 50k lines.
# Dummy functions for the examples. Real code is more complicated
function1 <- function(energy, stock, critical) {
if (stock < critical) {
return (energy)
} else {
return(0)
}
}
function2 <- function(power) {
return(round(power/100))
}
# Dummy data
d <- data.frame( "energy"= c(660, 660, 660, 660),
"stock" = c(20, 0, 0, 0),
"delivery" = c(0, 0, 2, 0),
"critical" = c(50, 50 ,50, 50),
"power" = c(0, 0, 0, 0),
"production" = c(0, 0, 0, 0) )
for (i in 1:length(d$energy)) {
# Computing power, based on CUURENT stock
d$power[i] <- function1(d$energy[i], d$stock[i], d$critical[i])
# Computing production
d$production[i] <- function2(d$power[i])
# Updating NEXT stock with current production / delivery
if (i < length(d$energy)) {
d$stock[i+1] <- d$stock[i] + d$production[i] - d$delivery[i]
}
}
View(d)