如何從shell調用R腳本(例如,從Node.js exec)並將結果導出爲JSON(例如返回Node.js)?從命令行無聲運行R,將結果導出到JSON
下面的R代碼基本上工作。它讀取數據,適合的模型,轉換參數估計到JSON,並把結果打印到stdout:
#!/usr/bin/Rscript --quiet --slave
install.packages("cut", repos="http://cran.rstudio.com/");
install.packages("Hmisc", repos="http://cran.rstudio.com/");
install.packages("rjson", repos="http://cran.rstudio.com/");
library(rjson)
library(reshape2);
data = read.csv("/data/records.csv", header = TRUE, sep=",");
mylogit <- glm(y ~ x1 + x2 + x3, data=data, family="binomial");
params <- melt(mylogit$coefficients);
json <- toJSON(params);
json
這是我想如何從節點調用它...
var exec = require('child_process').exec;
exec('./model.R', function(err, stdout, stderr) {
var params = JSON.parse(stdout); // FAIL! Too much junk in stdout
});
除R進程不會停止打印到標準輸出。我試過--quiet --slave --silent
這些都有所幫助,但還不夠。這裏是什麼發送到stdout:
The downloaded binary packages are in
/var/folders/tq/frvmq0kx4m1gydw26pcxgm7w0000gn/T//Rtmpyk7GmN/downloaded_packages
The downloaded binary packages are in
/var/folders/tq/frvmq0kx4m1gydw26pcxgm7w0000gn/T//Rtmpyk7GmN/downloaded_packages
[1] "{\"value\":[4.04458733165933,0.253895751245782,-0.1142272181932,0.153106007464742,-0.00289013062471735,-0.00282580664375527,0.0970325223603164,-0.0906967639834928,0.117150317941983,0.046131890754108,6.48538603593323e-06,6.70646151749708e-06,-0.221173770066275,-0.232262366060079,0.163331098409235]}"
What's the best way to use R scripts on the command line?
運行R --silent --slave CMD BATCH model.R
每個帖子下面還導致大量無關的文本打印到model.Rout
:
Run R script from command line
啊哈,就是這樣!最後一個小問題,有沒有辦法像'[1]「{\」value \「:[4.04458733165933,...' – prototype
]那樣壓制前導」'[1]'「這是標籤告訴你它的長度爲1 vector,並且它來自當你在命令行命名的時候發生的默認打印,如果你使用'cat(json)'而不是打印沒有標籤的原始字符串,並且它不會逃避引號無論如何你是想要的 – Spacedman