RSRubyを導入
RSRubyはRubyからRを呼び出すためのgemパッケージ。
統計解析の結果をRailsで....と思ったのが発端で試しに導入してみた。
Mac OX 10.5とUbuntu 9.10での導入メモ*1。
前提
Mac OS X
Rをパッケージでインストール
http://aoki2.si.gunma-u.ac.jp/R/begin.html
ruby, rubygemsはOS標準のものを使用(ruby 1.8.6 )
導入
R_HOMEという環境変数を~/.bash_profileに設定
R_HOME=/usr/lib/R (on Ubuntu Linux) R_HOME=/Library/Frameworks/R.framework/Resources (on OS X)
RSRubyはgemコマンドから導入。
includeとlibのパスを渡す必要あり。
Mac OS X
$ sudo gem install rsruby -- --with-R-include=/Library/Frameworks/R.framework/Headers --with-R-lib=/Library/Frameworks/R.framework/Libraries
使ってみる
$ irb >> require 'rubygems' => true >> require 'rsruby' => true >> r = RSRuby.instance => #<RSRuby:0x1832b28 @caching=true, @cache={"get"=>#<RObj:0x1832a88>, "helpfun"=>#<RObj:0x18321a0>, "help"=>#<RObj:0x18321a0>, "parse"=>#<RObj:0x1832830>, "TRUE"=>true, "NaN"=>NaN, "F"=>false, "FALSE"=>false, "NA"=>-2147483648, "T"=>true, "eval"=>#<RObj:0x1832754>}, @proc_table={}, @class_table={}, @default_mode=-1> >> r.methods => ["inspect", "get_fun", "_dump", "to_yaml_style", "clone", "method", "caching", "public_methods", "method_missing", "instance_variable_defined?", "equal?", "freeze", "caching=", "methods", "respond_to?", "__getitem__", "r_init", "dup", "instance_variables", "to_yaml", "__id__", "reset_cache", "object_id", "eql?", "to_yaml_properties", "help", "id", "proc_table", "with_mode", "shutdown", "singleton_methods", "send", "taint", "proc_table=", "frozen?", "instance_variable_get", "__send__", "instance_of?", "to_a", "__init_eval_R__", "type", "class_table", "protected_methods", "crash", "instance_eval", "delete_from_cache", "==", "display", "===", "class_table=", "instance_variable_set", "kind_of?", "extend", "to_s", "taguri", "default_mode", "hash", "eval_R", "class", "tainted?", "=~", "private_methods", "taguri=", "nil?", "untaint", "default_mode=", "[]", "is_a?"] >> r.c 1,2,3,4,5 => [1, 2, 3, 4, 5] >> r.matrix(0,10) => [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]] >> data = r.rnorm(10,2) => [3.16951127754536, 2.705635077864, 1.69203758603816, 0.463246272762254, 1.80113921512659, 2.68990215452311, 3.40352615884108, 3.81926313722047, 2.21245812353084, 2.95499646061802] >> r.plot(data) >> r.library()
ほうほう、結構できること多いみたい。eval_Rが動いてRでの関数を使っているのかなぁ?
入れ子になった配列を作ったり、ダミーデータ生成するのにも使い勝手が良さそう。
参考
http://d.hatena.ne.jp/okmount/20090130/1233251020
http://d.hatena.ne.jp/cuspos/20090520/1242825057
http://nsaunders.wordpress.com/2009/05/20/baby-steps-with-rsruby-in-rails/
*1:OSのバージョンはあまり関係ないと思う