Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent `<<- ` from assigning in the global environment?

Tags:

r

I've received a function that uses the dreaded <<-. Is there any way for me to sandbox it so that it doesn't change the global environment?

For example, I would like to find something so I can run f() without it changing the value of x:

x <- 0
f <- function()  x <<- 1
f()
x
# [1] 1

I tried evaluating it in an environment where the value was already defined:

local({
  x <- 2
  f()
})

But that doesn't seem to work. Is there a way for me to enclose this to protect the global environment?

like image 361
sebastian-c Avatar asked Jun 28 '17 09:06

sebastian-c


2 Answers

The assign <<- function will first look in the parent environment (of the one the function is) and upwards, in case it won't find any, it will create a new one the global environment.

So the trick is both to wrap f() in another function and define it inside, and also initialize a variable x in this wrapper function. Then it won't affect your x from the global environment:

x <- 0
wrapped_f = function(){
  x<-2
  function()  x <<- 1
  f()
  print(paste("new x=", x))
}
wrapped_f()
#### "new x= 1"
print(x)
#### [1] 0

And the same but without initializing x in the wrapper it will fail:

x <- 0
wrapped_f = function(){
  # x<-2
  f <- function()  x <<- 1
  f()
  print(paste("new x=", x))
}
wrapped_f()
#### "new x= 1"
print(x)
#### [1] 1
like image 187
agenis Avatar answered Sep 21 '22 11:09

agenis


We can try with exists to check if the variable is already defined globally.

f <- function()  {
   if(!exists("x"))
      x <<- 1
}
x <- 0
x
#[1] 0

f()

x
#[1] 0
like image 39
Ronak Shah Avatar answered Sep 20 '22 11:09

Ronak Shah