1

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.

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for answer. Unfortunately, I specifically mentioned that I want "assign_test" to create the variable in the environment of "exists_test" and NOT the global environment.
Awesome. Does exists() have a similar "pos" argument?
@Nova Maybe where = ...? I am not sure
1

Turns out, the pos and where arguments work when the input is sys.frame(-1). This was a nice little educational exercise in environment compartmentalization.

The code now works with those changes:


assign_fun <- function() {
  
  #check if "e" exists in the environment of "check_fun"
  if (exists(x = "e", where = sys.frame(-1))) {
    
    print(get("e", pos = sys.frame(-1)))

  } else {
    
    #If "e" DOESNT exist in the environment of "check_fun", then assign it to that environment
    assign(x = "e", value = 5, pos = sys.frame(-1))
    print("assigned")
    
    }
}
  

check_fun <- function() {
  
  for (i in 1:5) {
    
    assign_fun()
    
  }
  output <- get("e")
  print("output")
  print(output)
}

check_fun()

Answer inspired by user: ThomasIsCoding

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.