In a recent posting to r-devel, Prof. Brian Ripley of R-Core announced an interesting development (pun intended) for future versions of R. Several of the core utility scripts, such as INSTALL and REMOVE, have been converted from sh scripts or Perl into native R code.
You might not think of R as a utility scripting language, but it has many useful features that make it an excellent candidate for such a task, not least powerful string-processing tools and functions for manipulating file names. In fact, if you're familiar with programming in R, but (like me) can never remember the exact syntax for a loop in bash, you might be tempted to create your own command-line tools using R as the scripting language.
In Unix-like systems (including MacOS X), this is easy to do. Create an ordinary text file where the first line is #!/usr/bin/Rscript (replacing /usr/bin with your actual R executable installation directory). Then on the following lines include ordinary R commands. Set the executable bit of the file (with chmod +x), put it in your PATH, and you can then use it as an ordinary command-line tool.
Rscript is a noninteractive variant of the standard R command, designed for just this use. Here's an example (from the
Rscript documentation) that allows you to install packages from the shell prompt, without having to invoke interactive R:
#! /usr/bin/Rscript --vanilla --default-packages=utils
args <- commandArgs(TRUE)
res <- try(install.packages(args))
if(inherits(res, "try-error")) q(status=1) else q()
If you have some tasks that you need to automate from the command-line, Rscript might be a useful tool to make use of your R programming skills, without having to dive for the bash documentation. And as a bonus for scripts you intend to distribute to other R users, your script will be platform-independent, easy to maintain, and may even run faster than alternative scripting languages on platforms like Windows.
great, can pipes be used as well?
Posted by: jouke | June 04, 2010 at 08:23