0

In a R plumber script in which I use future I need to assign some variables to the global environment (so that a variable created in one API can be retrieved from another API) but it does not work as expected.

I created a simple example. Here you can see the main script to run in R:

### Set the asynchronous coding
library(promises) ; library(future)
future::plan("multisession")

## Plumber app
library(plumber)

pr <- pr("APIs_TestAsync.R")
pr %>% pr_run()

and here the script to save as "APIs_TestAsync.R":

#* Test 1
#* @get test1
#* @serializer unboxedJSON
#* @tag TestFuture
function() {
  
  # Create a dataset
  df<-data.frame(A=c("a", "a", "a", "b", "b", "c"), B=c(1,2,3,4,5,6))
  assign("Test1", df, .GlobalEnv)

  return(
    list(SUM=sum(df$B))
    )
  }


#* Test 2
#* @get test2
#* @serializer unboxedJSON
#* @tag TestFuture
function() {
  
  # Create a future promise
  Prom<-future({
    
      # Wait for 10 seconds (needed to test the asynchronous functions)
      Sys.sleep(10)
  
      # Create a dataset
      df<-data.frame(A=c("a", "a", "a", "b", "b", "c"), B=c(1,2,3,4,5,6))
      assign("Test2", df, .GlobalEnv)

      # Store the list in Prom
      return(
        list(SUM=sum(df$B))
      )

  }, seed=T) # Close future promise
  
  return(Prom) # Return Prom to the API

}

You'll see that the first API (not using future) manages to assign Test1 to the global environment but that the second API does not assign Test2.

I tried several ways of assignment, different environment names, explored the futureAssign function but did not manage to make it work...

If you have any idea it would be greatly appreciated!

Axeman
  • 32,068
  • 8
  • 81
  • 94
  • Impossible. The global environment of a parallel R worker is not the same as the global environment of the parent R process. All parallel frameworks in R works this way. You need to find other ways to transfer that object back to the parent R process. Your best bet is via the return value. Alt, save to file, if an option. – HenrikB Jan 13 '23 at 19:50
  • 1
    Thanks a lot for the answer, very clear and helpful! I'll save a RDS file locally to pass the information from one API to the other then. Thanks! – Victor Cazalis Jan 17 '23 at 13:21

0 Answers0