How can I prevent `<< -` from being assigned in a global environment?

I got a function that uses terrible <<-. Is there any way for me to isolate it so that it does not change the global environment?

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

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

I tried to evaluate it in an environment where a value has already been determined:

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

But that does not work. Is there any way for me to conclude this to protect the global environment?

+6
source share
3 answers

The assignment function <<-will first search in the parent environment (the one that is the function), and up, if it is not found, it will create a new global environment.

, , f() , x . x :

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

, x :

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
+5

. :

x <- -1
generator <- function(){
  x <- 0
  function()  x <<- 1
}

f <- generator()

f()
print(x)
# [1] -1
+2

exists , .

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

f()

x
#[1] 0
+2

All Articles