How do you create a progress bar when using the “foreach()” function in R?

前端 未结 7 1287
青春惊慌失措
青春惊慌失措 2020-11-28 03:41

there are some informative posts on how to create a counter for loops in an R program. However, how do you create a similar function when using the parallelized version wit

7条回答
  •  半阙折子戏
    2020-11-28 04:14

    You can also get this to work with the progress package.

    what it looks like

    # loading parallel and doSNOW package and creating cluster ----------------
    library(parallel)
    library(doSNOW)
    
    numCores<-detectCores()
    cl <- makeCluster(numCores)
    registerDoSNOW(cl)
    
    # progress bar ------------------------------------------------------------
    library(progress)
    
    iterations <- 100                               # used for the foreach loop  
    
    pb <- progress_bar$new(
      format = "letter = :letter [:bar] :elapsed | eta: :eta",
      total = iterations,    # 100 
      width = 60)
    
    progress_letter <- rep(LETTERS[1:10], 10)  # token reported in progress bar
    
    # allowing progress bar to be used in foreach -----------------------------
    progress <- function(n){
      pb$tick(tokens = list(letter = progress_letter[n]))
    } 
    
    opts <- list(progress = progress)
    
    # foreach loop ------------------------------------------------------------
    library(foreach)
    
    foreach(i = 1:iterations, .combine = rbind, .options.snow = opts) %dopar% {
      summary(rnorm(1e6))[3]
    }
    
    stopCluster(cl) 
    

提交回复
热议问题