Search code examples
pythonrjsoncdsw

Writing dictionary addition function in R


I need to write the equivalent of the following code in R but I'm not quite sure how to go about it:

def add(args):
  result = args["a"] + args["b"]
  return result

The reason why is because for the platform I am using (Cloudera Data Science Workbench) models need a JSON input to be able to call them using an API key

So if I write a test model in R such as:

f <- function(x, y) {
    return (x + y)
}

I cannot do a call like {"x" : 2, "y" : 4} using the httr package.

So I either need to make a dictionary like call for functions in R

OR

I am simply calling JSON incorrectly in which case could someone help me format that correctly for an API call

Thanks


Solution

  • Thanks @danlooo for the help. Along with my own research I came up with an answer that satisfies my question

    As the rest API needs a key-value pair format on CSDW, I can do the following taken from @danlooos answer:

    f <- function(l) {
        return (l$a + l$b)
    }
    
    f(list(a = 2, b = 3) # Returns 5
    

    This can be put into JSON format then for the API call as:

    {"a" : 2, "b" : 3}