1:转载自:https://zhuanlan.zhihu.com/p/24747506
循环中添加进度条,在用R语言做数据分析处理的过程中,我们经常会碰到一些数据量比较大进而导致循环执行好久的情况。等待的过程太煎熬了,最关键的是我们不知道现在已经完成了多少进度,从而决定是否停止重新修改代码。
library(tcltk) u <- 1:2000 #开启进度条 pb <- tkProgressBar("进度","已完成 %", 0, 100) for(i in u) { info<- sprintf("已完成 %d%%", round(i*100/length(u))) setTkProgressBar(pb, i*100/length(u), sprintf("进度 (%s)", info),info) } #关闭进度条 close(pb)
目前,还有一个新的包,叫做tcltk2,也可以是实现上述的功能,具体测试代码如下。可以更详细的设置进度栏的大小等属性值:
library(tcltk) library(tcltk2) root <- tktoplevel() l1 <- tk2label(root) pb1 <- tk2progress(root, length = 300) tkconfigure(pb1, value = 0, maximum = 9) tkgrid(l1, row = 0) tkgrid(pb1, row = 1) for (index in 1:10){ tkconfigure(l1, text = paste("Index", index)) tkconfigure(pb1, value = index - 1) Sys.sleep(1) }
2:sapply、lapply等添加 使用软件包 pbapply https://github.com/psolymos/pbapply
A lightweight package that adds progress bar to vectorized R functions (*apply
). The implementation can easily be added to functions where showing the progress is useful (e.g. bootstrap). The type and style of the progress bar (with percentages or remaining time) can be set through options. The package supports snow-type clusters and multicore-type forking (see overview here).