albertosantini / node-rio

Integration with Rserve, a TCP/IP server for R framework
https://github.com/albertosantini/node-conpa
MIT License
176 stars 35 forks source link

Passing multiple parameters to R function #37

Closed NilsFrkal closed 7 years ago

NilsFrkal commented 7 years ago

Hi experts,

I would like to call an R function which expects multiple parameters: 1. Array of Objects 2. Date. Is there a way to pass those 2 parameters directly or can I only pass 1 JSON object e.g. {ar: [{..},{..}], d: date }?

Thank you very much.

Nils

albertosantini commented 7 years ago

Interesting question and the answer is one literal object.

TLDR;

Generally speaking, it is better passing one object than a list of parameters.

It improves the readability because the signature of the function is short. Also the maintainability is better, because, if a parameter is added (or removed), you don't need to refactor the signature of the function, and the parameters are not based on the position.

Said that, evaluate has a config parameter with data property: as you know, data object is transformed to a stringified JSON, passed to an entrypoint (a R function) and used like a list in the R function after deserializing the argument passed as JSON string.

https://github.com/albertosantini/node-rio/blob/master/lib/evaluate.js#L33

There would not be any difference from the user perspective, if you may pass multiple arguments, because you need always to deserialize the parameters.

For instance, your proposal

getOptimalPortfolio <- function (prods, referenceDate, highs, lows) { 
   symbols = fromJSON(prods)
   refDate = fromJSON(referenceDate)
   highsConstraints = fromJSON(highs)
   lowsConstraints = fromJSON(lows)
...

vs. actual implementation

getOptimalPortfolio <- function (obj) { 
   o = fromJSON(obj)
   symbols = o$prods
   referenceDate = o$referenceDate
   ...
...

So passing one object is a best practice and a convenient way to handle the payload passed to the R function. There is a nice symmetry because in JS realm you use a literal object and in R realm you use a list containing the parameters: so in both world there is an idiomatic approach, but one point where the two worlds collaborate, fromJSON(obj).

It seems there is not any gain for the user using multiple args and it would add only some complexity in rio implementation.

Hope this helps.

NilsFrkal commented 7 years ago

Thanks a lot for the fast response. Agree with this, only the transformation of the array into the corresponding data.table structure in R gets more complicated.

Best, Nils

albertosantini commented 7 years ago

Thanks for the feedback.

If you have any proposal to manage array of objects in js and data.table in R, there is an open issue collecting suggestions, proposals and ideas about next 3.x version.