Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.9k views
in Technique[技术] by (71.8m points)

How to check if a variable exists in/assign a variable to a specific function's environment in R?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to put the assigned variable to the environment of caller function, you can use pos = sys.frame(-1) within assign, e.g.,

assign(x = "e", value = 5, pos = sys.frame(-1))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...