Given the function f() as follows:
f = function(a) {
  if(a > 0) b = 2
  c = exists('b')
  return(c)
}
How do I specify that the exists() function should only search within the function f?
With a blank environment, calling f(-5) will return FALSE as I would like, but if I do
b = "hello"
f(-5)
then I get TRUE. How do I get f(-5) to return FALSE even if the user has a b defined elsewhere in their script outside the function f?
I expect this has something to do with the where parameter of exists() but I can't figure out what is the proper environment to call for this parameter. I still haven't wrapped my head fully around environments in R...
Thanks!
Just use the inherits= parameter of exists. See the ?exists help page for more info
b <- 100
f <- function(a) {
  if(a > 0) b <- 2
  c <- exists('b', inherits=FALSE)
  return(c)
}
f(5)
# [1] TRUE
f(-5)
# [1] FALSE
                        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