R scoping: disallow global variables in function R scoping: disallow global variables in function r r

R scoping: disallow global variables in function


My other answer is more about what approach you can take inside your function. Now I'll provide some insight on what to do once your function is defined.

To ensure that your function is not using global variables when it shouldn't be, use the codetools package.

library(codetools)sUm <- 10f <- function(x, y) {    sum = x + y    return(sUm)}checkUsage(f)

This will print the message:

<anonymous> local variable ‘sum’ assigned but may not be used (:1)

To see if any global variables were used in your function, you can compare the output of the findGlobals() function with the variables in the global environment.

> findGlobals(f)[1] "{"  "+"  "="  "return"  "sUm"> intersect(findGlobals(f), ls(envir=.GlobalEnv))[1] "sUm"

That tells you that the global variable sUm was used inside f() when it probably shouldn't have been.


There is no way to permanently change how variables are resolved because that would break a lot of functions. The behavior you don't like is actually very useful in many cases.

If a variable is not found in a function, R will check the environment where the function was defined for such a variable. You can change this environment with the environment() function. For example

environment(sum) <- baseenv()sum(4,5)# Error in sum(4, 5) : object 'sUm' not found

This works because baseenv() points to the "base" environment which is empty. However, note that you don't have access to other functions with this method

myfun<-function(x,y) {x+y}sum <- function(x,y){sum = myfun(x+y); return(sUm)}environment(sum)<-baseenv()sum(4,5)# Error in sum(4, 5) : could not find function "myfun"

because in a functional language such as R, functions are just regular variables that are also scoped in the environment in which they are defined and would not be available in the base environment.

You would manually have to change the environment for each function you write. Again, there is no way to change this default behavior because many of the base R functions and functions defined in packages rely on this behavior.


You can check whether the variable's name appears in the list of global variables. Note that this is imperfect if the global variable in question has the same name as an argument to your function.

if (deparse(substitute(var)) %in% ls(envir=.GlobalEnv))    stop("Do not use a global variable!")

The stop() function will halt execution of the function and display the given error message.