我有一个 R 脚本,它查询数据库、运行一些分析、根据当前系统日期绘制一些图表。
我想让这个脚本每天在启动时运行,我想我可以很简单地使用带有必要参数的 rscript.exe 快捷方式来做到这一点。
这工作正常,但是脚本在运行后退出,对于查看图表不是很有用。
我用的是XP和win7。
有没有一种简单的方法可以将脚本的输出保留在屏幕上?我尝试将扫描合并到脚本中,但它不会暂停。
我知道我可以打开 rgui 并运行一行代码,但计划是将其部署到完全不熟悉 R 的同事的计算机上。
这适用于我在 Linux 上:
#!/usr/bin/env Rscript
X11()
with(mtcars, plot(mpg, hp))
locator(1)
用户必须在绘图窗口消失之前单击它。我认为它可以通过调用来在 Windows 上运行windows()
。
Michael 的解决方案可能已经奏效,但这里显示的是tkrplot框架内的情节。tkrplot包(在 CRAN 上)使用 R 的tcltk扩展并且随处可用。
# From http://stackoverflow.com/questions/3063165/
# r-building-a-simple-command-line-plotting-tool-
# capturing-window-close-events
require(tcltk)
library(tkrplot)
## function to display plot, called by tkrplot and embedded in a window
plotIt <- function(){ plot(x=1:10, y=1:10) }
tt <- tktoplevel() ## create top level window event handler
done <- tclVar(0) ## variable to wait on
## bind to the window destroy event, set done variable when destroyed
tkbind(tt,"<Destroy>",function() tclvalue(done) <- 1)
## Have tkrplot embed the plot window, then realize it with tkgrid
tkgrid(tkrplot(tt,plotIt))
tkwait.variable(done) ## wait until done is true
## script continues, or exits, ... once plot is closed
如果您查看 R 的 tcltk 文档,您会发现其他带有“确定”按钮以关闭等的示例。
Sys.sleep(1e30) 怎么样?那应该等待足够长的时间。
好的,我对我所看到的这类问题的所有答案完全不屑一顾,因为它们都没有在 Windows 上工作。readline, tkwait.window, Sys.sleep(1e30), while(TRUE),都没有用。
但是我刚刚将 R 更新到 v3.1.0,现在 tkwait.window(yourmainwindow) 可以工作,while(TRUE){} 可以工作,尽管 Sys.sleep(1e30) 仍然不起作用。
没关系...我正在使用 tkwait.window,因为它是 tk,并且正在等待我的窗口(这就是我想要的)。
从http://www.sciviews.org/_rgui/tcltk/OKtoplevel.html获取例如工作......(为简洁起见删除了评论)
require(tcltk)
tt <- tktoplevel()
OK.but <- tkbutton(tt, text = "OK", command = function() tkdestroy(tt))
tkgrid(OK.but)
tkfocus(tt)
tkwait.window(tt) # <-- added this to make the window stay!