显示一个计数器以显示一条显示行中的循环 [英] Display a counter for loops across one display line

查看:90
本文介绍了显示一个计数器以显示一条显示行中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以下品种的R中运行循环:

I am running loops in R of the following variety:

for(i in 1:N){...}

我想拥有一个在循环过程中显示i当前值的计数器.我希望这能跟踪到达循环末尾的距离.一种方法是简单地将print(i)插入循环代码中.例如,

I would like to have a counter that displays the current value of i in the progress of the loop. I want this to keep track of how far along I am toward reaching the end of the loop. One way to do this is to simply insert print(i) into the loop code. E.g.,

for(i in 1:N){
...substantive code that does not print anything...
print(i)
}

这可以完成工作,为您提供正在运行的i.问题在于它将每个值打印在新行la上,

This does the job, giving you the i's that is running. The problem is that it prints each value on a new line, a la,

[1] 1
[1] 2
[1] 3

这会占用大量控制台空间;如果N很大,它将耗尽所有控制台空间.我想拥有一个不会占用太多控制台空间的柜台. (有时候,可以向上滚动控制台以检查自己是否在运行自己认为正在运行的东西,这是很好的选择.)因此,我希望有一个显示为

This eats up lots of console space; if N is large it will eat up all the console space. I would like to have a counter that does not eat up so much console space. (Sometimes it's nice to be able to scroll up the console to check to be sure you are running what you think you are running.) So, I'd like to have a counter that displays as,

[1] 1 2 3 ...

在达到控制台宽度后继续上一行.我不时看到这一点.有什么技巧可以做到这一点?

continuing onto a new line once the console width has been reached. I have seen this from time to time. Any tricks for making that happen?

推荐答案

尝试使用函数flush.console()

Try to use the function flush.console()

for (i in 1:10){
 cat(paste(i, " ")); flush.console()
}

给予

1  2  3  4  5  6  7  8  9  10

对代码进行了小的修改,将仅打印一个数字并在每次运行时将其递增.它使用回车(\ r)序列来避免控制台中出现一长串数字.

Here a small modification to the code that will print only one single number and increment it with each run. It uses a carriage return (\r) sequence to avoid a long list of numbers in the console.

for(i in 1:100) {  
  Sys.sleep(.1)      # some loop operations
  cat(i, "of 100\r") 
  flush.console()
}

这篇关于显示一个计数器以显示一条显示行中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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