如何在ubuntu中安装的R中的循环内打印变量?

时间:2016-10-06 02:06:20

标签: r ubuntu

大约3年前,我们在这里提出了类似的问题How do I print a variable inside a for loop to the console in real time, as the loop is running, in R?。与我运行循环时的问题类似,它将每个输出变量显示到屏幕而不清除前一个。

a=matrix(c(1,8,2,5),nrow=2)
for(i in 1:4){
  print(a*i)
}
     [,1] [,2]
[1,]    1    2
[2,]    8    5
     [,1] [,2]
[1,]    2    4
[2,]   16   10
     [,1] [,2]
[1,]    3    6
[2,]   24   15
     [,1] [,2]
[1,]    4    8
[2,]   32   20

为简单起见,我只对低维矩阵使用了四次迭代,但我的真实for循环有超过1000次迭代和一个大维矩阵,这使得输出变得难看并且内存密集。

我在上面提出的问题中尝试了solution

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

但它没有改变我的R输出中的任何内容(安装在ubuntu中)并且它仍然打印出所有变量

注意:我不是在寻找进度条

2 个答案:

答案 0 :(得分:2)

可能是system('clear'),正如Function to clear the console in R的回答中所建议的那样。例如:

for(i in 1:10){
  system('clear')
  print(matrix(rnorm(9), nc = 3))
  Sys.sleep(0.5)
}

答案 1 :(得分:1)

Does this do what you want? I ran it on Debian (Ubuntu's mum), and it seemed to do the key tasks.

for(ii in 1:10) {
    Sys.sleep(1)
    cat(paste0('\r',ii))
}

It can also work in batch mode, if that's your thing. I put something similar into in a file, and ran it as R CMD BATCH --no-save myfile.R

for(ii in 1:10) {
    Sys.sleep(1)
    cat(paste0('\r',ii), file='/dev/tty')
}

The tricks:

  • \r returns you to the beginning of the line. In some environments, you might have to write that as '\\r', but I didn't find that with Debian running R from the console.
  • In batch mode, write to /dev/tty, not /dev/console

Hope that helps.