I have two functions, "assign_fun" and "check_fun." I am trying to use "assign_fun" to check if a variable exists in "check_fun." If it doesn't exist, then I'd like to create that variable in the "check_fun" environment, NOT the global environment.
I understand the exists()
and assign()
functions have an "environment" argument...but not sure what to put in there.
Here is my code:
assign_fun <- function() {
#check if "e" exists in the environment of "check_fun"
if (exists(x = "e")) {
print(e)
} else {
#If "e" DOESNT exist in the environment of "check_fun", then assign it to that environment
assign(x = "e", value = 5)
print("assigned")
}
}
check_fun <- function() {
for (i in 1:5) {
assign_fun()
}
output <- e
print(output)
}
Since "assign_fun" is within "check_fun", I think I basically just have to go up one compartment "level" to check and assign.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…