当循环在R中运行时,如何将for循环内的变量实时打印到控制台? [英] How do I print a variable inside a for loop to the console in real time, as the loop is running, in R?

查看:283
本文介绍了当循环在R中运行时,如何将for循环内的变量实时打印到控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,每次迭代都花很长时间,我想实时查看它的进度.当循环正在运行时,如何在for循环中实时将变量打印到控制台?在循环完成之后,这些命令中的每一个都将打印所有内容,这对我来说毫无用处:

I have a loop that takes a long time for each iteration, and I would like to see the progress of it in real time. How do I print a variable inside a for loop to the console in real time, as the loop is running? Each of these print everything after the loop is finished, which is useless for me:

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

推荐答案

最后一个确实可以实时打印,请尝试如下操作:

The last one does print in real time, try it like this:

for(i in 1:10){
  Sys.sleep(0.1)
  print(i)
}

这在Rstudio中看起来不错,但是在经典Rgui中,您必须单击控制台以刷新它(例如,通过Sys.sleep(0.5)增加睡眠有助于看到这一点).您可以使用flush.console清除缓冲区来避免这种情况:

This looks fine in Rstudio, but in classic Rgui you have to click the console in order to it to refresh (increasing the sleep for example by Sys.sleep(0.5) helps to see that). You can circumvent that by using flush.console which clears the buffer:

for(i in 1:10){
  Sys.sleep(0.1)
  print(i)
  flush.console() 
}

或者在Windows中,您可以在上方工具栏中选择Misc,然后取消选中buffered output.

Or in Windows you can select Misc in the upper toolbar and uncheck the buffered output.

如果您的目标是跟踪循环的过程,则在进行大量迭代时,上述方法(至少在我看来)有点笨拙.在这种情况下,最好使用进度条:

If your goal is to track the process of your loop, the above method feels bit akward (at least to my eyes) when you are running through large number of iterations. In that case it might be nicer to use progress bars:

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)

这篇关于当循环在R中运行时,如何将for循环内的变量实时打印到控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆