Wrapper to FOR loops with progress bar

前端 未结 8 694
走了就别回头了
走了就别回头了 2021-01-31 19:57

I like to use a progress bar while running slow for loops. This could be done easily with several helpers, but I do like the tkProgressBar from tcl

8条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 20:20

    Thanks for everyone for your kind answers! As none of those fit my wacky needs, I started to steal some pieces of the given answers and made up a quite customized version:

    forp <- function(iis, .fun) {
        .fun <- paste(deparse(substitute(.fun)), collapse='\n')
        .fun <- gsub(' <- ', ' <<- ', .fun, fixed=TRUE)
        .fun <- paste(.fun, 'index.current <- 1 + index.current; setTkProgressBar(pb, index.current, label=paste( round(index.current/index.max*100, 0), "% ready!"))', sep='\n')
        ifelse(is.numeric(iis), index.max <- max(iis), index.max <- length(iis))
        index.current <- 1
        pb <- tkProgressBar(title = "Working hard:", min = 0, max = index.max, width = 300) 
        for (i in iis) eval(parse(text=paste(.fun)))
        close(pb)
    }
    

    This is quite lengthy for a simple function like this, but depends only on base (anf of course: tcltk) and has some nice features:

    • can be used on expressions, not just functions,
    • you do not have to use <<- in your expressions to update global environment, <- are replaced to <<- in the given expr. Well,this might be annoying for someone.
    • can be used with non-numeric indexes (see below). That is why the code become so long :)

    Usage is similar to for except for you do not have to specify the i in part and you have to use i as index in the loop. Other drawback is that I did not find a way to grab the {...} part specified after a function, so this must be included in the parameters.

    Example #1: Basic use

    > forp(1:1000, {
    +   a<-i
    + })
    > a
    [1] 1000
    

    Try it to see the neat progress bar on your computer! :)

    Example #2: Looping through some characters

    > m <- 0
    > forp (names(mtcars), {
    +   m <- m + mean(mtcars[,i])
    + })
    > m
    [1] 435.69
    

提交回复
热议问题