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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With