R: Not to look for variables outside a function if they do not exist within it

Viewed 205

This function is OK in R:

f <- function(x) {
  x + y
}

Because if the variable y is not defined inside the function f(), R will look for it outside the environment of the function, in its parent environment.

Apart from the fact that this behavior can be a bug generator, what is the point of functions having input parameters? Anyway, all the variables inside a function can be searched outside of it.

Is there any way not to look for variables outside a function if they do not exist within the function?

2 Answers

Some reasons for using parameters that came to my mind:

  • Without parameters, users have to define variables before using the function, and these variable names need to match the variable names used within the function -- this is impractical.
  • How is anyone supposed to know/remember the names of the variables within a function? How do I know which variables within a function are purely local, and which variables have to exist outside of the function?
  • Input parameters can be passed directly as values or as a variable (and the variable name does not matter).
  • Input parameters communicate the intended usage of the function; it is clear what data is needed to operate it (or at the very least: how many values need to be inserted by the user of the function)
  • Input parameters can be documented properly using Rd files (or roxygen syntax)

I am sure there are many other reasons to use input parameters.

M. Papenberg provides a very good explanation.

Here's a quick addendum how to make a function not look for objects in parental environments:

Just provide them in the parameter list! This might sound stupid, but that's what you should always do unless you have good reason to do otherwise. In your example only x is passed to the function. So, if the idea here is that x should be returned if y doesn't exist, you can go for default parameters. In this case this could be done as

f <- function(x, y = 0) {
  x + y
}
Related