Is there any way to throw a warning (and fail..) if a global variable is used within a R
function? I think that is much saver and prevents unintended behaviours...e.g.
sUm <- 10
sum <- function(x,y){
sum = x+y
return(sUm)
}
due to the "typo" in return the function will always return 10
. Instead of returning the value of sUm
it should fail.
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.This will print the message:
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.That tells you that the global variable
sUm
was used insidef()
when it probably shouldn't have been.Another way (or style) is to keep all global variables in a special environment:
Then the function won't be able to get them:
But you can always use them with globals$:
To manage the discipline, you can check if there is any global variable (except functions) outside of
globals
: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 exampleThis works because
baseenv()
points to the "base" environment which is empty. However, note that you don't have access to other functions with this methodbecause 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.
Using
get
is a way:Output:
Having the right
sum
in the get function would still only look inside the function's environment for the variable, meaning that if there were two variables, one inside the function and one in the global environment with the same name, the function would always look for the variable inside the function's environment and never at the global environment: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.
The
stop()
function will halt execution of the function and display the given error message.