4

I frequently develop a function by first developing a script that works for a specific dataset, and then turn the script into a function by wrapping it in function_name <- function(...) {do_something}, and test whether the function works as a function (rather than as a set of scripts).

While developing the script, it often happens that some objects are created in the global environment (e.g., intermediary variables in a set of calculations). This creates the risk that, when I test the coe as a function, I think the function works well, but in reality it only does so because it accesses objects that only exist in the global enviroment. Without them being present in the global environment, the function fails.

As a result, I frequently restart my R session and test the function in the fresh and clean environment. However, this becomes annoying when I need to constantly do that.

My question: is there a way that I can run a function while limiting its access to the global environment? For example, perhaps I could create a new environment, assign the function to it, assign the data that it requires as input to that environment, and then run the function restricted to this limited environment? I am hoping there are efficient ways to test a function--while it is still under full development--making sure it works without accessing objects that happen to exist in the global environment.

Any ideas?

Steve G. Jones
  • 325
  • 2
  • 10

0 Answers0