Friday, 23 October 2009

RSPerl : Using R from within Perl

Some things I write in perl some in R, sometime I use perl to write R and run R. One thing that I find very useful is the functionality of RSPerl which enables you to call R functions from within perl and on perl variables. It can also call perl from R, though I have no idea why you would want to do this.

My main use is to carry out statistical tests on the results of things carried out in. For example I use perl to run patser to count the number of hits to a position weight matrix in a test sequence and a background sequences, then I use RSPerl to calculate the p-value via the binomial test (binom.test function).

It was a pain to setup, as I had to recompile R and install various modules in the correct places and setup some environment variables. Once working though it is a great tool. You can even use R's great graphical capabilities to automatically generate figures from data in perl variables.

perl -e 'use R;&R::initR("--silent","--vanilla");&R::eval("r <- rnorm(100);plot(r,pch=20)");'

This one plots a histogram of the length of perl scripts!

for f in *.pl; do wc -l ${f}|cut -f 1 -d " "; done | perl -ne 's/\n/,/g;print;' |perl -ne 'use R;&R::initR("--silent","--vanilla");chop;&R::eval("hist(c($_),main=\"File Lengths\",xlab=\"Number of Lines\")");sleep 10'



  1. Hi,
    How did you make the setup?
    It makes me craky. It's possible to make some simple functions (mean,sum) but you can't make a t-test.There is a bug...I don't know to solve it.
    If you remember how you did it...

  2. I just followed the instructions really. It wasn't too bad, though I did need to re-compile R to make the shared library and set all the environment variables.
    To be honest I don't use it any more and just use perl to write and run short R scripts as it is more likely to work on other platforms than RSPerl.