The R statistical library provides a large number of statistical analysis and visualisation techniques. Examples of the functions include: matrix and array operations, such as multiplication, eigenvalue computation and singular value decomposition; statistical modelling; ANOVA and variance analysis; and maximum likelihood models, to name a very few. There are also tools to create impressive and informative visualisations. R's home page is http://www.r-project.org/

I normally recommend installing the latest version from source, but I have yet to get R-2.9.0 working with RSRuby. Perhaps later. On Ubuntu Linux, install R from synaptic by finding the package 'r-base-core' and installing with all dependencies.

Run R simply by typing the command 'R' at the command prompt. To see some pretty pictures enter 'demo(graphics)' at R's command prompt. When finished, 'quit()' returns you to your shell prompt. You probably don't want to save the initial workspace.

The bridge is called RSRuby, written by Alex Gutteridge, and is available from RubyForge at http://rubyforge.org/projects/rsruby/ I downloaded the rsruby gem to my computer, and then installed RSRuby from rubygems by typing:

sudo gem install rsruby-0.5.1.1.gem -- --with-R-dir=/usr/lib/R/ --with-R-include=/usr/share/R/include/

The flags are needed, as else the libraries are not found by gem. Now, vital step:

- cd ~
- edit the file .bashrc
- add the line 'export R_HOME=/usr/lib/R' to the end of the file
- save the file
- close the command window
- reopen

This correctly sets the R_HOME environment variable. Just setting R_HOME before running ruby does not work: you will get "Fatal error: R home directory is not defined" as soon as you try to create an instance of RSRuby.

Finally, a simple example of using R from Ruby. Start up irb:

irb(main):001:0> require 'rsruby' => true irb(main):002:0> r = RSRuby.instance => ##, "T"=>true, "TRUE"=>true, "F"=>false, "FALSE"=>false, "parse"=>#, "eval"=>#, "NA"=>-2147483648, "NaN"=>NaN, "help"=>#, "helpfun"=>#} irb(main):006:0> r.assign('x', 3) => 3 irb(main):007:0> r.x => 3 irb(main):008:0>

Not very exciting, but seems to work!

Here's a script which does some calculation in R, and then creates and saves a graph. The script can be put into a file and run from Ruby.

require 'rsruby' r = RSRuby.instance # construct data to plot, graph of x vs sqrt(x) xs = 10.times.collect {|i| i} ys = xs.collect {|x| r.sqrt(x)} r.png("example.png") # tell R we will create png file r.plot(:x => xs, :y => ys, # (x,y) coordinates to plot :type=> "o", # draw a line through points :col=> "blue", # colour the line blue :main=> "Plot of x against sqrt(x)", # add title to graph :xlab => "x", :ylab => "sqrt(x)") # add labels to axes r.eval_R("dev.off()") # finish the plotting