Victor Cz
Victor Cz

Reputation: 76

R plumber with future promise: assign variable to global environment

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!

Upvotes: 0

Views: 504

Answers (0)

Related Questions