Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
###############################################################
total <- 10
for(i in 1:total){
print(i)
Sys.sleep(0.1)
}
###############################################################
Unfortunately this does not work as the console output to the basic R GUI is buffered. This means that it is printed to the console at once after the loop is finished. The R FAQs (7.1) explains a solution: Either to change the R GUI buffering settings in the Misc menu which can be toggled via <Ctrl-W> or to tell R explicitly to empty the buffer by flush.console(). So like this it works:
###############################################################
total <- 20
for(i in 1:total){
Sys.sleep(0.1)
print(i)
# update GUI console
flush.console()
}
###############################################################
Of course it would be even nicer to have a real progress bar. For different progress bars we can use the built-in R.utils package. First a text based progress bar:
###############################################################
total <- 20
# create progress bar
pb <- txtProgressBar(min = 0, max = total, style = 3)
for(i in 1:total){
Sys.sleep(0.1)
# update progress bar
setTxtProgressBar(pb, i)
}
close(pb)
###############################################################
To get a GUI progress bar the tkProgressBar() function from the tcltk package can used.
###############################################################
total <- 20
# create progress bar
pb <- tkProgressBar(title = "progress bar", min = 0,
max = total, width = 300)
for(i in 1:total){
Sys.sleep(0.1)
setTkProgressBar(pb, i, label=paste( round(i/total*100, 0),
"% done"))
}
close(pb)
###############################################################
Last but not least, a progress bar using the Windows operating system.
###############################################################
# create progress bar
pb <- winProgressBar(title = "progress bar", min = 0,
max = total, width = 300)
for(i in 1:total){
Sys.sleep(0.1)
setWinProgressBar(pb, i, title=paste( round(i/total*100, 0),
"% done"))
}
close(pb)
###############################################################
Ciao, Mark
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
