Using R from the shell

From Theory of Measurements Wiki

Jump to: navigation, search

Update: rinterp has been implemented and it obsoletes nearly everything here: [1]

Introduction

Even though R is fairly self contained, it is often necessary to combine it with other tools. One powerful method to do this integration is using the unix shell environment, this way it is possible treat R files just as one would treat any other shell script.

How it is done

This is not as easy as one might guess, as the following doesn't work:

#!/usr/bin/R --slave --vanilla < 
cat("hello world\n")

Examination of the man pages for execve give us the reason, /usr/bin/R is a shell script, and thus not a valid interpreter:

       execve() executes the program pointed to by filename.   filename  must  be
       either  a  binary executable, or a script starting with a line of the form
       "#! interpreter [arg]".  In the latter case, the  interpreter  must  be  a
       valid  pathname for an executable which is not itself a script, which will
       be invoked as interpreter [arg] filename.

To remedy this, we create a small wrapper: Note: there seems to another, possibly better way to implement rshell: [2].

#include <stdio.h>

/* 
 * R_HOME has to be defined. Usually it is /usr/lib/R
 * todo: copy all command line params to R
 */
int main(int argc, char **argv)
{
  /* should be enough for all */
  char cmd[2048];
  FILE *out;
  char l;
          
  strcpy(cmd,"/usr/lib/R/bin/exec/R --vanilla --slave < ");
  strcat(cmd,argv[1]);
  
  
  out=popen(cmd,"r");
  l = fgetc(out);
  printf("%c",l);
  while(l != EOF) 
  {
          l = fgetc(out);
          if(l !=EOF)
                printf("%c",l);
                
  }
  pclose(out);
}

Compile and copy it:

gcc -o rshell rshell.c ; sudo cp rshell /usr/bin ; sudo chmod 755 /usr/bin/rshell

and then set the environment variable R_HOME=/usr/lib/R.


Finally, now we can execute our hello.R:

#!/usr/bin/rshell
cat("Hello world")
> ./hello.R
Hello world

Personal tools