Can data be saved between calls to the openCPU server?

415 views Asked by At

I understand that the interface to OpenCPU is RESTful. Nevertheless, I would like to save data between function calls, if possible.

I naively created the following package:

vals <- c()

fnInit <- function() {
  vals <<- c('a','b','c')
}

but I got the error: cannot change value of locked binding for 'vals' when I called the fnInit function. I understand why this is happening.

I then tried:

fnBoth <- local({
  vals <- c('a','b','c')
  function(which) {
    if (which == 0) {
      vals
    } else if (which == 1) {
      vals <<- c(vals,'d')
      vals
    }
  }
})

but every time I POST to the fnBoth function with which = 1, I get the same response: [1] "a" "b" "c" "d"

If I call the function again, I get the same answer. So, it would seem that the value vals is being reset each time.

My question is: Can data be saved between function calls? The above attempts are not meant to be exhaustive - maybe there's another technique? Or, should I simply save the value to disk?

Thanks

1

There are 1 answers

3
Jeroen Ooms On

It is not completely clear to me what you are trying to accomplish, perhaps you can elaborate a bit on the type of application you wish to build.

OpenCPU supports chaining of function calls to calculate e.g. f(g(x), h(y)). This is done by passing the session ID of a completed call as an argument to a subsequent one. Have a look at the docs about argument formats: https://public.opencpu.org/api.html#api-arguments. It includes an example that illustrates this by calculating summary(read.csv("mydata.csv")):

#upload local file mydata.csv
curl https://public.opencpu.org/ocpu/library/utils/R/read.csv -F "[email protected]"

#replace session id with returned one above
curl https://public.opencpu.org/ocpu/tmp/x067b4172/R/.val/print
curl https://public.opencpu.org/ocpu/library/base/R/summary -d 'object=x067b4172'

The first request calls the read.csv function which returns a dataframe. In the last line, we call the summary function where we set the object argument equal to the output of the previous call (i.e. the data frame) by passing the session ID.