我有一个简单的R脚本.当它通过Rscript.exe运行时,默认情况下它正在绘制为PDF文件.我希望脚本打开一个绘图窗口.
我使用命令:
Rscript.exe tmp_plot.R
Run Code Online (Sandbox Code Playgroud)
r文件tmp_plot.R包含:
x <- 1:10
y <- sin(x)
plot(x,y)
Run Code Online (Sandbox Code Playgroud)
Rei*_*son 18
您正在以非交互方式运行R - Rscript用于脚本 - 因此默认的绘图设备是pdf(),不是x11()或者您的操作系统默认设置(windows()通过它的外观).然而,打开替代设备是微不足道的; 用x11()或windows().在尝试编写将在屏幕上显示绘图的脚本时遇到的问题是,在显示的示例代码中,脚本在绘制绘图时立即终止,无论是在屏幕上还是在pdf()设备上显示.充其量你可以让它暂停使用Sys.sleep(),例如:
x <- 1:10
y <- sin(x)
x11() ## or windows()
plot(x,y)
Sys.sleep(10)
Run Code Online (Sandbox Code Playgroud)
我认为你这是错误的方式.如果你想在运行一个R"脚本"时想要交互性,我指的是一组执行某些分析的R语句,你最好在你的操作系统上获得一个编辑器/ IDE,它允许你逐步完成脚本或者一次代码块,加上与正在运行的R会话交互.我使用Emacs和ESS扩展.您可以考虑使用Tinn-R或RStudio作为替代品.
Rscript 用于运行不需要人工交互或干预的脚本或类似批处理的作业.
library(tcltk) # for message box and thus hold-open functionality
x11() # for Linux, see documentation for other operating systems
# first plot
# second plot
# hold-open functionality prevents script from exiting user acts
prompt <- "hit spacebar to close plots"
extra <- "some extra comment"
capture <- tk_messageBox(message = prompt, detail = extra)
Run Code Online (Sandbox Code Playgroud)
如果你不喜欢规定的计时器的想法,上面的脚本只会在按键(空格键或输入)或用户点击鼠标(确定按钮)时退出.