Sunday 24 February 2013

Installing R Language support in Ruby

The R Language is a similar (yet open source) version of Metalab's MATLAB. R is available on most platforms, and there is a binding Gem for Ruby called RSRuby.

The installation is easy enough once you have R correctly installed.

Here are the steps on Ruby 1.8.7, with Gems >1.8 (probably the same on all version).

If you just try the basic Gem installation you get:

sudo gem install rsruby
Fetching: rsruby-0.5.1.1.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing rsruby:
ERROR: Failed to build gem native extension.

        /usr/bin/ruby1.8 extconf.rb
checking for main() in -lR... no

ERROR: Cannot find the R library, aborting.

*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/bin/ruby1.8
--with-R-dir
--without-R-dir
--with-R-include
--without-R-include=${R-dir}/include
--with-R-lib
--without-R-lib=${R-dir}/lib
--with-Rlib
--without-Rlib

So you need to add some appropriate switches to enable the builder to find the R libraries.

Assuming you have R already installed, they are likely (under Ubuntu) to be at:

/usr/lib/R                       = binaries
/usr/share/R/include       = build libraries

First create an environment variable for the R binaries:

~$ export R_HOME=/usr/lib/R

then add this to your load path:

~$ export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:R_HOME/bin

Now, retry the installation:

~$ sudo gem install rsruby -- --with-R-dir=/usr/lib/R --with-R-include=/usr/share/R/include
Building native extensions.  This could take a while...
Successfully installed rsruby-0.5.1.1
1 gem installed
Installing ri documentation for rsruby-0.5.1.1...
Installing RDoc documentation for rsruby-0.5.1.1...

Test out the rsruby gem:

~$ irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'rsruby'
=> true
irb(main):003:0> r = RSRuby.instance
=> #-2147483648, "parse"=>#, "help"=>#, "NaN"=>NaN, "FALSE"=>false, "TRUE"=>true, "eval"=>#, "F"=>false, "T"=>true, "helpfun"=>#, "get"=>#}, @proc_table={}, @class_table={}, @default_mode=-1>
irb(main):004:0> r.help
=> "/usr/lib/R/library/base/help/NULL"
irb(main):005:0> exit

Just remember to set R_HOME permanently for your user in wherever you choose to add environment variables.