Home > OS >  How to use object from another function in a function without explicitely passing it to the function
How to use object from another function in a function without explicitely passing it to the function

Time:06-13

I'm sure there's already an answer to it, but I'm not sure about the right terms to search for.

I thought that in R, functions that need an argument that is not defined in the function will look for said argument in the environment they are called from / the parent environment, no?

So I thought, the following would work:

f_xyz <- function (y, z)
{
  x   y   z
}

f_x <- function()
{
  x <- 1
  y <- 2
  z <- 3
  f_xyz(y, z)
}

f_x()

x is defined and created in the f_x function, so when calling the f_xyz function WITHIN f_x, I thought it will find x there and use it. However, that is not the case. Instead I'm getting an error Error in f_xyz(y, z) : object 'x' not found.

If I create the f_xyz function in f_x, the error doesn't appear.

What am I missing?

f_x <- function()
{
  f_xyz <- function (y, z)
  {x   y   z}
  
  x <- 1
  y <- 2
  z <- 3
  f_xyz(y, z)
}

f_x()

[1] 6

CodePudding user response:

R uses lexical scoping:

the values of free variables are searched for in the environment in which the function was defined.

Function f_xyz was defined in the global env, but x was defined in the env of f_x, resulting in the error 'object not found'. In the latter case, both f_xyz and x were defined in the same scope, so they can share their arguments.

Other languages like Python use enclosing scopes for nested functions, but R doesn't. See here for details.

Nevertheless, you probably want to use partial evaluation to set some arguments and mention x explicitly in the function. It is very messy to write a function relying on something else than its arguments.

  • Related