How to define global variables across multiple functions in R? (Not in a package environment)

Viewed 126

I have a project in R where I am creating a variety of functions and I have a set of constants that I use in a lot of these functions.

How can I define global variables so they are used across all of my functions? Currently I have to redefine them every time.

Would creating a function for each constant work? Or can I create some kind of constants file and load that in?

1 Answers

That depends. If you're simply using scripts, I believe the best way would be to have a "main" script that calls the others and create a global variable (your "constant"). Something like:

global_constant <<- 12345

However, if you're developing an R package, consider creating a function that uses the R options and defines such behavior when the package is loaded. As described here:

.onLoad <- function(libname, pkgname) {
    options(var1='blablabla', var2=12345)

}
Related