Home > Back-end >  return global object from function
return global object from function

Time:03-13

I know <<- can be used to assign local variable to have global scope, however I want to understand the reverse whether its possible to access global variable inside function, an example below to illustrate what I mean. Any way to do this in R without reassigning it inside function as a global variable

Expected output: z is a global variable

z = "z is a global variable."

z_function = function(){
   z <- "z is a local variable"
  return(z)
}

z_function()

CodePudding user response:

R has a "search path" if there is no scoped variable of the same name, the global environment will be searched for the symbol. Because you are assigning a scoped variable within your function with the same name as the global variable the function will return the local variable as it is found in the search path first. Functions order their own { scope } higher in the search path

z <- "Global"
z_fun <- function() z

> z_fun()
[1] Global

z_fun2 <- function() {z <- "Scoped"; return(z)} 
> z_fun2() 
[1] "Scoped"

CodePudding user response:

I don´t know if I understand your question correctly, but if R does not find a variable inside the function it will look in the environment and "search" the variable name.

So the following code gives "z is a global variable"

z <- "z is a global variable."

z_function = function(){
   ## z <- "z is a local variable"
  return(z)
}

z_function()
  • Related