Make R (statistics package) wait for the keyboard prompt when run in bash script

I use R to create a series of graphs in a loop, when the user presses the enter key to indicate that they have seen the graph, and it's time to move on. These are interactive rotation graphs created using the rgl package, and therefore using something like Sys.sleep () is not good enough.

I can currently use readline (), which works when I run R interactively. However, if I want to run an R script within a bash script, all graphs will blink in front of the screen. This happens if I call R using:

R --no-save -f myfile.r R --no-save -e "source('myfile.r')" R --no-save << myfile.r 

How do I get R to pause and wait for the user to hit at startup as a bash subprocess?

+7
source share
5 answers

Use this:

 readLines("stdin", n = 1) 

This will result in a real stdin instead of using stdin() .

I would call it with:

 Rscript myfile.r 
+3
source

It was a late answer, but my goal was similar: running Rscript should call the rgl window with the plot and nothing else, and it should stay there until the window closes, i.e. rgl window should not end.

To achieve this, I just put this at the end of the R script, and the rgl graph will remain there for manipulation until you exit the window, consuming a little CPU time:

 play3d(function(time) {Sys.sleep(0.01); list()} ) 

For regular 2D plots, locator() works similarly or locator(1) if one click should close the plot window.

+3
source

I'm not sure if there is an easy way to wait for keyboard input, but at least you can wait for the mouse .
Not elegant, but try this script:

 quartz() # or maybe windows() in windows for (i in 1:5) {plot(i, i); locator(1)} 
+2
source

Here is an example script that works for me (tested your first call method on Windows). It uses the tcltk package and creates an additional small window with a single button, the script pauses (but still allows you to interact with the rgl window) until you click the continue button, pressing the key while this window is active, then continue using the script .

 library(tcltk) library(rgl) mywait <- function() { tt <- tktoplevel() tkpack( tkbutton(tt, text='Continue', command=function()tkdestroy(tt)), side='bottom') tkbind(tt,'<Key>', function()tkdestroy(tt) ) tkwait.window(tt) } x <- rnorm(10) y <- rnorm(10) z <- rnorm(10) plot3d(x,y,z) mywait() x <- rnorm(100) y <- rnorm(100) z <- rnorm(100) plot3d(x,y,z) mywait() cor(x,y) 
+1
source

plot.lm uses devAskNewPage(TRUE) ; perhaps it will also work here.

0
source

All Articles