Home > Software engineering >  Writing dictionary addition function in R
Writing dictionary addition function in R

Time:10-08

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

CodePudding user response:

JSON is the default data format for most REST APIs. We can serialize an R list to JSON using the jsonlite package. The other way of creating an R list based on a json string is also possible:

library(jsonlite)

# named lists
l <- list(x = 2, y = 4)
l
#> $x
#> [1] 2
#> 
#> $y
#> [1] 4
c <- "{\"x\":3,\"y\":5}"
c
#> [1] "{\"x\":3,\"y\":5}"

toJSON(l, auto_unbox = TRUE)
#> {"x":2,"y":4}
fromJSON(c, simplifyVector = TRUE)
#> $x
#> [1] 3
#> 
#> $y
#> [1] 5

# vector without names
toJSON(c(1,2,3), auto_unbox = TRUE)
#> [1,2,3]
fromJSON("[4,5,6]", simplifyVector = TRUE)
#> [1] 4 5 6

Created on 2021-10-07 by the reprex package (v2.0.1)

CodePudding user response:

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}

  • Related