Home > R > Look ma! No typing! Autorunning code on R startup

Look ma! No typing! Autorunning code on R startup

Regular readers may know that I often make R-based GUIs. They’re great for giving non-technical users safe and easy access to statistical models. The safety comes from the restrictions of a GUI: you can limit what the users does more easily than with a command line, helping to reduce the number of opportunities for bad science. My tool of choice for GUI building is John Verzani’s set of gWidgets packages; see my introduction and comparison with Deducer.

Since the target audience is non-technical, an important aim is to reduce the amount of typing at the R command prompt. Typically, I wrap the GUI into package, and have a single function call to load the GUI, so the users will have to start R, then type something like

library(myGui)
gui <- runTheGui()

#Here's an example GUI to play with now
runTheGui <- function()
{
  win <- gwindow("Test", visible = FALSE)
  rad <- gradio(letters[1:4], cont = win)
  visible(win) <- TRUE
  focus(win)
  list(win = win, rad = rad)
}

Typing two lines isn’t too onerous, but the ideal situation would involve no typing at all. That is, you double click a shortcut that opens R and then the GUI. With a little help from the internet, I have two solutions. Which one is best depends upon your setup.

The first solution was suggested to me by my collaborators Simon and Mark over at Drunks & Lampposts, who got it from Greg Snow. I’ve refined the technique to make it simpler.

There are two tricks involved. Firstly, when R (at least R GUI; Eclipse, RStudio, emacs, etc. may require configuration) starts up, by default it will run a function named .First, if that function exists. So our first task is to put those previous lines of code inside that function.

.First <- function()
{
  library(myGui)
  gui <<- runTheGui()
}

Then, we save that function into an R binary workspace file.

save(.First, file = "~/Desktop/runTheGui.RData")

The second trick is that (assuming your operating system has been configured correctly), double-clicking a .RData file will start R GUI, loading said .RData file, and running the contents of that .First function.

So all the user needs to do is double click the RData file, and the GUI will run.

This is exactly what we wanted, but it has a small drawback in that R GUI isn’t available on all platforms. Also, if you really don’t want users to type things, then you may not want R GUI at all. In that case, using Rscript (as suggested by Dirk Eddelbuettel) is a better solution. Rscript is a little bit like batch mode. It open R in a terminal, runs a script, then closes R again. So for this solution, we need to create a script. This time we don’t need to wrap the contents inside a function. We do need to add something to the end of the script to prevent R closing down once the script has run, such as a check that the window is still open. (Note that since the R console won’t be available this time, this solution isn’t that useful for non-GUI purposes.)

library(myGui)
gui <- runTheGui()
while(isExtant(gui$win)) Sys.sleep(1)

Now to get the GUI running, you create a shortcut to Rscript, with the script file as an argument. Change the path to R and to the script file as appropriate.

"%ProgramW6432%\R\R-2.15.1\bin\Rscript.exe" "path/to/your/script/runTheGui.R"

And voila! We have a GUI running in R, again from a simple, single double-click, and this time R closes itself down when the GUI closes.

About these ads
Tags: , , ,
  1. Russ
    24th July, 2012 at 12:00 pm

    Hi there,

    Great post, thanks for sharing. I’m trying running up the learning curve on R… and want to do something similar-but-different and wonder if something like the above might help.

    I don’t need a GUI interface per sae, I just want the user to open an *.RData workspace which automatically runs some code (either by sourcing a proceedure, or just running a function) which spits out some CSVs then closes again. Any thoughts on a simple way of doing this?

    • 24th July, 2012 at 14:27 pm

      In that case you just need a script that runs your analysis. That is, you want an R file that contains something like


      library(somePackage)
      source("some analysis file.R")
      load("my data.RData")
      dfr <- read.csv("my other data file.csv")
      ans <- analyse(dfr)
      write.csv(ans, "results file.csv")

      Then open up an OS console window (DOS or bash prompt) and call either R CMD BATCH my_script_file.R or Rscript my_script_file.R.

      Once you have that working, you can craete a batch file (.BAT) containing that command, so the user double clicks it and the script runs.

      • Russ
        24th July, 2012 at 16:06 pm

        OK, thanks for taking the time to explain. You make it sound rather simple! I’ll give it a go :o)

  2. Anonymous
    13th September, 2012 at 20:09 pm

    Hey Thanks for the post! very helpful!

  3. marvin
    17th September, 2012 at 15:17 pm

    Thank, this works, except is has problems loading some packages – do you have any suggestions?

    • 1st November, 2012 at 8:59 am

      Sorry, I only just noticed your comment. Which packages can’t you load? (The “myGui” package in the post was just an example name – it doesn’t actually exist.)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 217 other followers

%d bloggers like this: