rplumber

Plumber API calling multiple source files


I am trying to setup an API to that sources multiple scripts in R based on inputted data like so

#* @post /test
function(req) {
  source("R Scripts/packages.r")
  ###############
  source("R Scripts/functions.r")
  ###############
  source("R Scripts/selection.r")
  ###############
  source("R Scripts/calculation.r")
  ###############
  source("R Scripts/graphing.r")
}

The end goal is for someone on my website to enter in a name which passes through to R, reads in all the packages, functions, reads some data filtering out by the inputted name, save that data, calculate some values based off the filtered data and then graph the calculations.

The way I have set it up above creates an issue in the source("R Scripts/selection.r") section as this is where I want to pass on the name that I have selected but I get the following error eval(ei, envir): object 'req' not found>

If I were to write source("R Scripts/selection.r", req), I get new a error data <- fread("name.csv"): could not find function "<-"> which implies that my previous packages have not been read.

If I try to read in the packages in that specific script, I get this error library(tidyverse): could not find function "library">.

I am a bit at a loss.

Any help would be appreciated.


Solution

  • Good news,

    I managed to figure it out! In order to solve the environment issue you simply have to add (.., local = TRUE) to the source command. Use the case example above,

     #* @post /test
    function(req) {
      source("R Scripts/packages.r", local = TRUE)
      ###############
      source("R Scripts/functions.r", local = TRUE)
      ###############
      source("R Scripts/selection.r", local = TRUE)
      ###############
      source("R Scripts/calculation.r", local = TRUE)
      ###############
      source("R Scripts/graphing.r", local = TRUE)
    }
    

    The reason for this is that plumbr creates its own environment that is not associated(?) with the .GlobalEnv. When we specify (.., local = TRUE) the source command determines that the expression should be evaluated in the environment from which the source is called.