simpler
simpler (“simple R”) is a lightweight wrapper that calls R (really Rscript) from within ruby. It is designed to favor R in syntax.
Why use this rather than rsruby?
You should probably be using rsruby–it’s a fantastic gem. However, if you want to code using more of an R code sytax (e.g., to cut and paste R code and have it just work), or if you can’t get rsruby working, this gem may be useful to you.
Examples
FYI - the API is still a little unstable.
Basic execution (Raw input, raw output)
require 'simpler'
r = Simpler.new
r.eval! { "mean(c(1,2,3))" } # -> "[1] 2\n" (a Simpler::Reply object)
Using ruby variables (calculating correlation coefficient):
x = [1,2,7]
y = [3,4,8]
reply = r.eval!(x,y) {|xr,yr| "cor(#{xr},#{yr})" } # -> "[1] 0.9994238\n"
Any object that has a #to_r method can be passed in. Currently, Array and Simpler::DataFrame are the only objects with this method defined, but one can go really far with only these two data types.
Show a plot
Simpler uses Rscript to run R commands. So, all plots that would normally go to X11 are saved to “Rplots.pdf”. show! is precisly the same as eval!, but it also opens “Rplots.pdf” with @pdf_viewer:
r.pdf_viewer = "acroread"
r.show!(x,y) {|xr,yr| "plot(#{xr}, #{yr})" }
Using DataFrames
hash = {
:one => [1,2,6,7],
:two => [3,4,2,9],
:three => [3,1,1,7],
}
df = Simpler::DataFrame.new(hash)
r.show!(df) {|dfr| "plot(#{dfr})" }
One can also make a data frame from an array of structs with Simpler.from_structs
When Errors Arise
On an R error, raises a Simpler::RError that returns the R error message and shows the R code submitted. (the @command queue is still cleared)
r.eval! { "plot(c(1,2,3),c(1,2))" }
Credit
Simpler is loosely inspired by the original gnuplot and, of course, the excellent rsruby.
Casting
All replies are of class Simpler::Reply, so casting can be done in a way that works for you by defining your own methods.
Copyright
Copyright © 2010 John Prince. See LICENSE for details.