8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

runrでRからRuby, Python等他言語のコードを実行する

Last updated at Posted at 2016-08-09

概要

Rではknitrというパッケージを用いてRの実行結果をドキュメントとして作成し、RPubs等で共有することができます。この時にRだけではなく他の言語の実行結果も出力できるようにするためのパッケージがrunrです。これは、knitr専用ということではなくて通常通り一つのパッケージとして使い、他言語のコードの実行結果をR側で得ることができます。現在対応しているのは

  • Bash
  • Julia
  • Python
  • Ruby

のみです。言語間ブリッジというほど高度なものではなくて、RubyならRuby側でTCPサーバを立ててRとソケット通信をし実行結果をR側に返すというだけのものです。

runrのインストール

install.packages経由ではインストールできないため、Githubのリポジトリからdevtoolsでインストールします。

install.packages("devtools") # devtools未インストールの場合

library(devtools)
install_github("yihui/runr")

使用例

試しにRubyのコードを実行してみます。

$ R
> library(runr)
> rb = proc_ruby()
> rb$start() # ruby側でTCPサーバ立ち上げ
> rb$exec("1 + 1") # Rubyのコード実行(標準出力に何も出てない場合は実行したコードだけが表示される)
1 + 1
> rb$exec("a = 1..8", "a") # 複数の文もok
a = 1..8
a
> rb$exec("print a.inject(:+)") # print等で標準出力に出力すると結果が返ってくる
print a.inject(:+)
# 36
> rb$stop() # サーバを閉じる

# 36 がコメントアウトされてるみたいになってますが、実際に36という値が返ってきています。

実際にknitrと使う例に関しては以下のRPubsの例を参考にすると良いでしょう。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?