【问题标题】:R : Display plot while calculating [duplicate]R:计算时显示图[重复]
【发布时间】:2014-09-30 07:50:07
【问题描述】:

我写了一个 R 脚本,它做了很多繁重的计算。该脚本进入一个 while 循环并执行大约 16 次(平均一个循环持续 3 到 5 分钟)。

我希望能够“跟踪”计算进度:能够看到已经完成了多少,还有多少还有待完成。所以我只是打印了迭代次数和完成循环的计算时间。

我想补充的是一种“进度条”,我用 ggplot2 直方图表示。每次计算完成时,我都会更新绘图(“完成”区域变大,“剩余”区域随后减小),然后打印它。但是,当函数仍在执行时,R studio 的“绘图”区域中没有显示任何绘图。一旦完成(16 个循环的)整体计算,所有图就会出现。

所以我的问题是:即使“整体”计算没有结束,是否可以在 while 循环结束时显示绘图?

如果我不清楚,请告诉我。

提前感谢您的回答。

编辑:Sys.sleep() 非常符合我的意图。

如果有人对代码感兴趣,下面是:

# Big calculation

iter <- iter + 1
d <- data.frame(x1 = c(1,1), x2 = c(iter/maxIt, 1 - iter/maxIt), 
                x3 = c("finished", "remaining"))
print(qplot(d$x1, d$x2, fill = factor(d$x3), geom = "histogram", stat = "identity"))
Sys.sleep(1)

# Preparing the next loop

【问题讨论】:

  • 必须是ggplot吗,见txtProgressBar
  • 谢谢,Sys.sleep() 做得很好。
  • 您对加快循环速度的方法感兴趣吗?矢量化、预分配和并行化可能会产生很大的不同。

标签: r plot while-loop


【解决方案1】:
timearray <- NULL # array of time used by each iteration
for (wait in c(3,2,5,4,6)) {
    s <- Sys.time() # iteration time start
    Sys.sleep(3) # do your calculation -- I just wait here
    s <- Sys.time() - s # now s is last iteration time
    timearray <- c(timearray, s) # add this new value to array
    plot(timearray, type='h', main='Iteration time') # plot the array
}

会是这样吗?

【讨论】:

  • Sys.sleep() 完美运行:它让 R studio 有足够的时间在计算下一个循环之前更新绘图窗口。
猜你喜欢
  • 1970-01-01
  • 2020-01-12
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 2017-07-27
  • 1970-01-01
相关资源
最近更新 更多