Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test for existence of a variable within a function's environment?

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!

like image 623
CephBirk Avatar asked Jun 28 '15 02:06

CephBirk


1 Answers

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
like image 191
MrFlick Avatar answered Oct 31 '22 19:10

MrFlick