QBoard » Artificial Intelligence & ML » AI and ML - R » Writing dictionary addition function in R

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

      November 24, 2021 12:20 PM IST
    0
  • 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}
    
    
      November 25, 2021 11:45 AM IST
    0
  • 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
      December 4, 2021 1:18 PM IST
    0
  • In that vectors, matrices, lists, etc. behave as "dictionaries" in R, you can do something like the following:

    > (x <- structure(c(5,2),names=c("a","b"))) ## "dictionary"
    a b 
    5 2 
    > (result <- outer(x,x,function(x1,x2) x1^2+x2))
       a  b
    a 30 27
    b  9  6
    > result["b","a"]
    [1] 9

     

    If you wanted a table as you've shown in your example, just reshape your array...

    > library(reshape)
    > (dfr <- melt(result,varnames=c("x1","x2")))
      x1 x2 value
    1  a  a    30
    2  b  a     9
    3  a  b    27
    4  b  b     6
    > transform(dfr,val1=x[x1],val2=x[x2])
      x1 x2 value val1 val2
    1  a  a    30    5    5
    2  b  a     9    2    5
    3  a  b    27    5    2
    4  b  b     6    2    2
    
      December 8, 2021 10:25 AM IST
    0