我有一个循环,每次迭代需要很长时间,我希望实时看到它的进展。当循环运行时,如何实时将for循环中的变量打印到控制台?在循环结束后,每个都打印出来,这对我来说是无用的:
for(i in 1:10){
write(i,stdout())
}
for(i in 1:10){
write(i,stderr())
}
for(i in 1:10){
print(i)
}
1
2
3
4
5
6
7
8
9
10
答案 0 :(得分:17)
最后一个实时打印,试试这样:
for(i in 1:10){
Sys.sleep(0.1)
print(i)
}
这在Rstudio中看起来很好,但在经典的Rgui中你必须单击控制台才能刷新它(例如通过Sys.sleep(0.5)
增加睡眠有助于看到它)。您可以通过使用清除缓冲区的flush.console
来解决这个问题:
for(i in 1:10){
Sys.sleep(0.1)
print(i)
flush.console()
}
或者在Windows中,您可以在上方工具栏中选择Misc
,然后取消选中buffered output
。
如果您的目标是跟踪循环过程,那么当您运行大量迭代时,上述方法感觉有点不合适(至少在我看来)。在这种情况下,使用进度条可能更好:
n<- 1000
pb <- txtProgressBar(min = 0, max = n, style = 3) #text based bar
for(i in 1:n){
Sys.sleep(0.001)
setTxtProgressBar(pb, i)
}
close(pb)
甚至更好的东西:
library(tcltk)
n<- 1000
pb <- tkProgressBar(title = "Doing something", min = 0, max = n, width = 200)
for(i in 1:n){
Sys.sleep(0.001)
setTkProgressBar(pb, i, label=paste(round(i/n*100,1),"% done"))
}
close(pb)
答案 1 :(得分:3)
cat函数允许您创建有用的复杂语句来跟踪脚本中的进度
for(i in 1:10){
ptm0 <- proc.time()
Sys.sleep(0.5)
ptm1=proc.time() - ptm0
jnk=as.numeric(ptm1[3])
cat('\n','It took ', jnk, "seconds to do iteration", i)
}
>It took 0.49 seconds to do iteration 1