1.plumberのインストール
> install.packages("plumber")
> library(plumber)
2.RScriptの作成
テスト用のスクリプトを生成します。注意:最後のカッコの後に1行必要みたいです。
[ha.R]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#* @get /ha | |
ha <- function() { | |
return("Hello API!") | |
} |
> source('~/Test01/ha.R')
> r <- br="" ha.r="" plumb="">> r$run(port=8000)
(Test01はプロジェクト名)
ブラウザでアクセスしてみます。
http://サーバURL:8000/ha
グラフを表示してみます。
[ api_graph.R]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#* @get /graph | |
#* @png | |
graph <- function(){ | |
plot(sin, -pi, 2*pi) | |
} |
> source('~/Test01/api_graph.R')
> r <- api_graph.r="" br="" plumb="">> r$run(port=8000)
ブラウザでアクセスします。
http://サーバURL:8000/graph
これでRの結果を他のシステムで表示できます。
これを例えばcakephpで表示する場合はViewに次のように書きます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php echo $this->Html->image('http://サーバURL:8000/graph01',array('width'=>'900','height'=>'500')); ?> |
localhost:8000とやってもうまく表示されませんでした。
あとは起動を素早くするために、plumberを関数化しとくといいです。
例えばgraph.Rを作った時に
[exe.R]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exe <- function(){ | |
library(plumber) | |
r <- plumb("graph.R") | |
r$run(port=8000) | |
} |
としておけば、exe()で実行できます。
課題
・exe()を実行してからでないとグラフが表示されない
ポート指定して実行なので、仕方ないですが、バックグラウンドで常に実行しておきたいと思って
$ Rscript --slave --vanilla exe.R
$ nohup R CMD BATCH exe.R &
など試したのですが、ループなどを設けないとすぐ終了してしまいます。
当面、グラフが必要な時は、サーバの負担も考えて、exe()を実行してからグラフを見るようにしたいと思います。解決できれば嬉しい。
参考
https://www.rplumber.io/
http://uribo.hatenablog.com/entry/2016/03/12/213000
0 件のコメント:
コメントを投稿