title: Testing existence of variable that is explicitly passed to a function in R
body: <p>I want to test for the existence of a variable that is explicitly passed to a function. The task is proving trickier than I expected. The problem is that I want the default argument to be <code>NULL</code>, and I also want users to be able to explicitly pass a <code>NULL</code> value. But if users instead try to pass a variable that doesn't exist –– for example, if they misspell a variable when calling the function –– it too will be NULL in the function, and in this case, I will want my function to stop with an error.</p>
  
  <p>Here is a simple example. It uses the <code>iris</code> dataset, which has a <code>Species</code> variable but not a <code>species</code> variable. With one exception, described below, the function here does what I want. But it is clunky and it doesn't explicitly test for existence, which worries me. Is there a better way?</p>
  
  <pre><code>data(iris)
  myFunc &lt;- function (x = NULL) {
    if (!missing(x)) {  # if x was explicitly passed by user
      xName &lt;- deparse(match.call()$x)
      if (xName != 'NULL' &amp;&amp; is.null(x)) {
        stop("The variable doesn't seem to exist.")
      }
      else print("x was explicitly passed, and there are no problems.")
    }
    else print("x was not passed by the user.")
  } 
  
  myFunc(x = NULL)          # "x was explicitly passed, and there are no problems."
  myFunc(x = iris$Species)  # "x was explicitly passed, and there are no problems."
  myFunc(x = iris$species)  # "The variable doesn't seem to exist."
  y &lt;- iris$species
  myFunc(y)                 # "The variable doesn't seem to exist."
  </code></pre>
  
  <p><br>
  Two further notes: </p>
  
  <ul>
  <li>I would like <code>z &lt;- NULL; myFunc(z)</code> to return "x was explicitly passed, and there are no problems." Instead, it returns an error ("The variable doesn't seem to exist."). I can probably get around this by adding code that checks for the existence of <code>z</code> in the calling environment—something like <code>exists(z, envir = parent.frame())</code>)—but is there a better way?</li>
  <li>I would like to use <code>exists()</code> to test for the existence of the <code>x</code> object, but it doesn't seem flexible enough. For example, <code>exists(iris)</code> works, but <code>exists(iris$Species)</code> returns <code>FALSE</code> even though I'd like it to return <code>TRUE</code> for this purpose.</li>
  </ul>