Wednesday, 20 April 2011

How to Source an R script automatically on a Mac using Automator and iCal

I wrote an R script that pulled data from an RSS feed.  The RSS feed updated frequently, so I wanted to be able to schedule the script to run automatically.  After some tinkering, I got it to work by implementing the steps below.  Note that these steps assume you do not want to save your workspace - that you are saving the objects you need explicitly within the script. 

Step 3: The Run Shell Script Action
  1. Test your R script in regular ole' R to make sure it runs without error.
  2. Add a quit(save="no") command at the end of your script. 
  3. Open Automator  (Applications -> Automator)
  4. Select Application from the Template Selection menu
  5. Select the Run Shell Script Action, double click or drag it over
  6. Type:  Rscript --no-save --no-restore /Users..../YourScript.R
    • The last argument should be the path of the script file you want to run
    • The 2nd and 3rd arguments tell R not to save the workspace when it's done and not to restore previously saved objects on startup, respectively
    • To see a full list of arguments you can pass to Rscript, just open Terminal and type Rscript 
  7. You can test your "Application" now by hitting the Run button in the upper right corner.  Ignore the little robot's warning.  Hopefully, you'll see some green checkmarks and a "Workflow completed" message.
  8. Save your "Application" somewhere clever.
  9. Now, open iCal and create a new event.  Set the date, time, and repeat values as you wish.  Select alarm->Open File.
  10. It will default to iCal; click iCal, select Other, and navigate to your "Application," which you saved somewhere clever.
That's it, you're done.  When the scheduled time comes, the script will run in the background without even opening R.  You may see a little gear up top on your menu bar, that's it.  

1 comment:

  1. Life Saver... Very insightful and better than buying third party apps.....

    ReplyDelete