Skip to content

Instantly share code, notes, and snippets.

@PhilOwen
Last active April 30, 2017 15:52
Show Gist options
  • Save PhilOwen/a877a13301bce337490f3b8b91b485d0 to your computer and use it in GitHub Desktop.
Save PhilOwen/a877a13301bce337490f3b8b91b485d0 to your computer and use it in GitHub Desktop.
RをF#から呼んでみる

Mac上のMonoから、Rを呼んでみる。

Rの統計関係の関数や簡単な描画機能は、たまに使いたくなることがある。
だが、Rは統計向けなので、イベントやネットワークといった、 一般のプログラミングでよくやる手法がイマイチわかりにくい。 とはいえ、その勉強にわざわざ労力を割きたくもない
.NetからRを呼ぶR.NETというライブラリがあるので、 それを使うのが良さそう。 逆に、Rから.Netを使うには、R側のパッケージがあるらしい。

MonoとRは、brewでインストールした。

brew install mono
brew install homebrew/science/r

R.NETはNuGetでダウンロードしてきた。

brew install nuget
nuget install R.NET.Community

ただ、/Library/Frameworks内にR.frameworkが 存在することが前提になっているらしく、 このままだと実行時にコケる。 R.frameworkがCellarに入っているので、 そこへシンボリックリンクを張った。

sudo ln -s /usr/local/Cellar/r/3.4.0/R.framework /Library/Frameworks/R.framework

以下で実行。

fsharpi \
-r:R.NET.Community.1.6.5/lib/net40/RDotNet.dll \
-r:R.NET.Community.1.6.5/lib/net40/RDotNet.NativeLibrary.dll \
-r:DynamicInterop.0.7.4/lib/net40/DynamicInterop.dll \
r.fsx

F#側で用意したデータをRに渡して、 Rのplot()関数で描画する。
すぐに描画されないことがあるので、 コンソールで何かキーが入力されるのを待っている。 こうするとなぜかうまく描画される。

手数が多めで落とし穴もあって、なんか微妙だ…

References

open RDotNet
open System
let xs = [for i in 1..1000 -> 0.03 * float i]
let ys =
let f x = exp (0.04*x) * sin x
List.map f xs
REngine.SetEnvironmentVariables()
using(REngine.GetInstance()) (fun engine ->
let toVector (xs: float seq) = engine.CreateNumericVector(xs)
engine.SetSymbol("xs", xs |> toVector)
engine.SetSymbol("ys", ys |> toVector)
engine.Evaluate("plot(xs, ys, type='l')") |> ignore
// bug?
Console.ReadLine() |> ignore
engine.Evaluate("ys") |> ignore
Console.ReadLine() |> ignore
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment