I\'m implementing an algorithm that involves lots of adding and removing things from sets. In R, this is slow because as far as I know, adding or removing things from a vect
If you can, initializing a vector so that it has length equal to its maximum length during the algorithm may help.
e.g.
vec <- rep(NA,10)
vec[1:3] <- 1:3
vec[4:5] <- 4:5
vec[6:10] <- 6:10
rather than
vec <- 1:3
vec <- c(vec,4:5)
vec <- c(vec,6:10)
compare
> system.time({vec <- rep(NA,10^4); for (i in 1:(10^4)) vec[i] <- i })
user system elapsed
0.043 0.001 0.044
to
> system.time({vec <- NULL; for (i in 1:(10^4)) vec <- c(vec,i) })
user system elapsed
0.249 0.089 0.335