Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make R (statistics package) wait for keyboard prompt when run within a bash script

I am using R to generate a series of plots within a loop, with the user hitting the enter key to indicate they have seen the plot and it is time to move on. These are interactive rotatable plots generated with the rgl package and therefore using something like Sys.sleep() is not good enough.

Currently I can use readline() which works find when running R interactively. However, if I want to run my R script within a bash script all the plots appear flashing before the screen. This happens whether 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 when run as a bash subprocess?

like image 802
Setjmp Avatar asked Oct 04 '11 21:10

Setjmp


2 Answers

Use this:

readLines("stdin", n = 1)

That will get the real stdin instead of what stdin() uses.

I'd invoke it with:

Rscript myfile.r
like image 113
Michael Hoffman Avatar answered Oct 29 '22 22:10

Michael Hoffman


It's a late answer but my goal was similar: Rscript execution should bring up an rgl window with a plot and nothing else, and it should remain there till the window is closed, i.e. the rgl window should not terminate.

To achieve this, I simply placed this at the end of the R script, and the rgl plot will remain there for manipulation until you quit the window, consuming little CPU time:

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

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

like image 38
Robert Monfera Avatar answered Oct 30 '22 00:10

Robert Monfera