I am having trouble optimising a piece of R code. The following example code should illustrate my optimisation problem:
Some initialisations and a function definitio
The reason that using rbind
in a loop like this is bad practice, is that in each iteration you enlarge your solution
data frame and then copy it to a new object, which is a very slow process and can also lead to memory problems. One way around this is to create a list, whose ith component will store the output of the ith loop iteration. The final step is to call rbind on that list (just once at the end). This will look something like
my.list <- vector("list", nrow(myframe))
for(i in 1:nrow(myframe)){
# Call all necessary commands to create values
my.list[[i]] <- values
}
solution <- rbind(solution, do.call(rbind, my.list))