0

I am trying to setup a simple connect between a NodeJS application and an R-script. So far I've managed to set up the basic connection and the running of the cript, by using r-script (found on npm).

However, I am not able to pass a simple json to the R so that it can be converted to a dataframe using jsonlite.

NodeJS Code:

var R = require("r-script");

var out = R("script.R")
  .data({"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"},  {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"}, {}, {"Name" : "Bowser", "Occupation" : "Koopa"})
  .callSync();

console.log(out);

script.R:

library("jsonlite")
mydf <- fromJSON(input[[1]])

This gives the output:

 'Argument 'txt' must be a JSON string, URL or file.'

I have tried removing the indexation of the vector (and give the full list to the fromJSON) but it also doesn't work.

Has anyone sucessfully passed JSON to an R script with this npm module?

Thanks in advance!

EDIT: Also, if place the JSON between "'", it gives me "trailing errors" in spaces, and if they are removed, on the { char.

Diogo Santos
  • 780
  • 4
  • 17

2 Answers2

2

I have no idea about how R works, however the error could point to the fact that what you are trying to pass is a javascript object, not a JSON. Javascript objects look like but are not identical to JSONs (see discussion here Javascript object Vs JSON)

One thing that you can try is passing in the data function a JSON string by calling the JSON.stringify function on your objects. Something like this:

var R = require("r-script");

var out = R("script.R")
  .data(JSON.stringify({"Name" : "Mario", "Age" : 32, "Occupation" : "Plumber"}), JSON.stringify( {"Name" : "Peach", "Age" : 21, "Occupation" : "Princess"}),JSON.stringify ({}), JSON.stringify({"Name" : "Bowser", "Occupation" : "Koopa"}))
  .callSync();

console.log(out);

It's a longshot but it shows a general direction on which you can debug

1

I managed to found a simple solution, the Manos Agelidis answer did put me in the right direction.

Basically, I have able to parse the input string using:

string = paste(input, collapse=",") 
string = paste("[",string,"]")
frame = fromJSON(string)

and in NodeJS:

  var out = R("script.R")
  .data('{"Name":"Mario","Age":32,"Occupation":"Plumber"}',
  '{"Name":"Peach","Age":21,"Occupation":"Princess"}',
  '{}',
  '{"Name":"Bowser","Occupation":"Koopa"}')
  .callSync();

fromJSON requires a vector but in string form, and not a literal vector. Therefore, what I needed to do what to create a string using the elements of the input and to add [ and ] to the begging and end of the string, respectively. This did convert to a data frame properly.

Diogo Santos
  • 780
  • 4
  • 17