Efficiently adding or removing elements to a vector or list in R?

前端 未结 4 795
予麋鹿
予麋鹿 2020-12-31 06:22

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

4条回答
  •  我在风中等你
    2020-12-31 07:06

    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
    

提交回复
热议问题