R, Statistics

Single script executable file in R for Windows

The scripting is flexible in Linux and Mac OS, but not in Windows. Executables in Windows OS depend on file name extension (the name after the last period).
The RScript interpreter can not be specified as “#!/usr/bin/RScript”.  So, usually in Windows, two files are required to execute a script file like R. An R script and a BAT file.

I introduce here, a trick to combine these two files into a single R script. This is useful if you are using multiple version of R (ex. 2.15.3 and 3.0.0), or want to add option arguments of Rscript.exe.

Sample 1: minimum, when a path to Rscript.exe can be searched

rem <- function(...) invisible(T)
rem( '
Rscript.exe %~F0
rem ')
### above=BAT, below=R

cat('Hello, World', rnorm(1), file='hello.txt')

Sample 2: explicit path for Rscript.exe is needed

rem <- function(...) invisible(T)
rem( '
"C:%S%bin%S%R%S%R-2.15.3%S%bin%S%i386%S%Rscript.exe" %~F0
rem ')

helloWorld <- function(x) {
  barplot(rnorm(3,7,5), col=rainbow(3))
  text(2, 5, x, cex=4, col='goldenrod')

helloWorld("Hello, World")

Use a file extension “.bat” for above examples, such as “sample1.bat”.

The idea is a keyword “rem”. This means a comment line in Windows Bat file, so the line is ignored. A variable “%~F0” is a full path of the bat file itself. So this script calls Rscript.exe with giving itself as R script file. Lines after “EXIT /B” is ignored as a Bat file. As an R script, The whole Bat section is put into a string.
But as the string is evaluated in R, it is regulated by the R grammar. The most sensitive point is the use of escape character “\”. While the back slash character is used as a path separator in Windows, the R handle it as an escape character.
By this reason, we cannot write an explicit “\” at the Bat section. The 2nd example uses a trick to solve this problem, with setting the character into a variable S.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s


This entry was posted on April 20, 2013 by and tagged , , , , .
The stupidest thing...

Statistics, genetics, programming, academics


R, Statistics

%d bloggers like this: