2

How might I call an R script from the shell (e.g. from Node.js exec) and export results as JSON (e.g. back to Node.js)?

The R code below basically works. It reads data, fits a model, converts the parameter estimates to JSON, and prints them to 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

Here's how I'd like to call it from Node...

var exec = require('child_process').exec;
exec('./model.R', function(err, stdout, stderr) {
   var params = JSON.parse(stdout);  // FAIL! Too much junk in stdout       
});

Except the R process won't stop printing to stdout. I've tried --quiet --slave --silent which all help a little but not enough. Here's what's sent to 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?

Running R --silent --slave CMD BATCH model.R per the post below still results in a lot of extraneous text printed to model.Rout:

Run R script from command line

Community
  • 1
  • 1
prototype
  • 7,249
  • 15
  • 60
  • 94

1 Answers1

3

Those options only stop R's own system messages from printing, they won't stop another R function doing some printing. Otherwise you'll stop your last line from printing and you won't get your json to stdout!

Those messages are coming from install.packages, so try:

 install.packages(-whatever-, quiet=TRUE)

which claims to reduce the amount of output. If it reduces it to zero, job done.

If not, then you can redirect stdout with sink, or run things inside capture.output.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
  • Aha, that's it! Last minor, is there a way to suppress the leading "`[1] `" as in `[1] "{\"value\":[4.04458733165933,...` – prototype Jun 19 '15 at 17:00
  • 1
    That's the label telling you its a length-1 vector, and that comes from the default print that happens when you name something on the command line. If you `cat(json)` instead it will print the raw string with no labels. Also, it won't escape the quotes which might be what you want anyway... – Spacedman Jun 19 '15 at 17:03