how to speed up an R for loop?

前端 未结 2 863
醉酒成梦
醉酒成梦 2021-02-10 14:34

I am running the following for loop for the gwr.basic function in the GWmodel package in R. What I need to do is to collect the mean of estimate parameter for any given bandwidt

2条回答
  •  遇见更好的自我
    2021-02-10 14:55

    Besides using parallelization as Matt Bannert suggests, you should preallocate the vector LARentMean. Often, it's not the for loop itself that is slow but the fact that the for seduces you to do slow things like creating growing vectors.

    Consider the following example to see the impact of a growing vector as compared to preallocating the memory:

    library(microbenchmark)
    
    growing <- function(x) {
      mylist <- list()
      for (i in 1:x) {
        mylist[[i]] <- i
      }
    }
    
    allocate <- function(x) {
      mylist <- vector(mode = "list", length = x)
      for (i in 1:x) {
        mylist[[i]] <- i
      }
    }
    
    microbenchmark(growing(1000), allocate(1000), times = 1000)
    # Unit: microseconds
    #          expr      min       lq      mean   median       uq       max neval
    # growing(1000) 3055.134 4284.202 4743.4874 4433.024 4655.616 47977.236  1000
    # allocate(1000)  867.703  917.738  998.0719  956.441  995.143  2564.192  1000
    

    The growing list is about 5 times slower than the version that preallocates the memory.

提交回复
热议问题