1

I'd like to save an R function to disk such that when the enviroment is cleared, I can load() the function and restore both the function itself, as well as any dependencies needed to execute the function. Currently, I can load the function itself, but none of the functions dependencies are restored, so invoking the function fails. Looking for either a package or guidance on how to implement this in R/Rcpp

In other words, looking for an R version of How to pickle a python function with its dependencies?

E.g

testDep=5

testFn = function() {
  return(2+testDep)
}

save(testFn, '/tmp/testfn.Rdata')

# --- Clear the env ---

load('/tmp/testfn.Rdata')
testFn()
kdkavanagh
  • 41
  • 5
  • How is this related to Rcpp? – Ralf Stubner Oct 04 '19 at 15:02
  • 1
    Since `testDep` is a free variable, it's not part of the `testFn`; it's not really a"dependency" they way R looks at it. You'd have to save the entire work space, or create a closure to hold the variable. Or you could save both variable `save(testFn, testDep, '/tmp/testfn.Rdata')` but that would inflate `testDep` back to your global environment on load. – MrFlick Oct 04 '19 at 15:03
  • Ideally I'd like to find a way to prune the environment to only the variables needed to run the function (or needed to run functions called by the main function, recursively) - My use case typically involves environments with some massive variables that wouldnt be necessary for the functions being serialized. FWIW, totally fine with inflating those variables back after loading the function/env – kdkavanagh Oct 04 '19 at 15:07
  • There are existing questions about finding all free variables inside a function: https://stackoverflow.com/questions/25373447/how-to-detect-free-variable-names-in-r-functions. You can just be sure to serialize all those values. Or really, if that's a primary use case for you, i'd strongly recommend rewriting the code not to be dependent on free variables on the first place. Closures are relatively easy way to encapsulate all the values you need into an environment. – MrFlick Oct 04 '19 at 15:33
  • Agreed that will find free variables, but also need to identify required function calls as well. Will give this a try in combination with the link above: https://stackoverflow.com/questions/11872879/finding-out-which-functions-are-called-within-a-given-function – kdkavanagh Oct 04 '19 at 16:23

0 Answers0