Running R Scripts with Plots

21,674

Solution 1

If you use the Rscript command (which is better suited for this purpose), you run it like this:

#!/usr/bin/Rscript

daq = read.table(file('mydata.dat'))
X11()
pairs(daq)

message("Press Return To Continue")
invisible(readLines("stdin", n=1))

Make sure to set the execute permission on myscript.r, then run like:

/path/to/myscript.r

or without the shebang:

Rscript /path/to/myscript.r

Solution 2

You could add a loop that checks for the graphical device every n seconds:

while (!is.null(dev.list())) Sys.sleep(1)

This will sleep until you close the plot window.

Solution 3

This is not a perfect solution, but you may call locator() just after the plot command.
Or just save the plot to pdf and then invoke pdf viewer on it using system.

Solution 4

One solution would be to write the plot out to pdf instead:

pdf(file="myplot.pdf")

##your plot command here
plot( . . . )

dev.off()
Share:
21,674
Stephen Diehl
Author by

Stephen Diehl

I work with Haskell, functional compilers, and type systems. I'm also on Twitter.

Updated on April 26, 2020

Comments

  • Stephen Diehl
    Stephen Diehl about 4 years

    I have a small shell script (bash) which runs a R script which produces a plot as output. Everything works fine but immedietly after the plot is rendered R quits. Is there a way to keep the R session alive until the plot window is closed.

    The shell script.

    #!/bin/bash
    R --slave --vanilla < myscript.r
    

    And the R script.

    daq = read.table(file('mydata.dat'))
    X11()
    pairs(daq)
    //R Completes this and then exits immediately.
    

    Thanks in advance for any help!