title: How can I reference the local environment within a function, in R?
body: <p>[This question has been resolved in the <a href="https://chat.stackoverflow.com/transcript/message/2307138#2307138">chat room, by Spacedman</a>, but I'm posting it for others' benefit in the future.]</p>
  <p>I have a function, <code>myFunc</code>, which creates <code>localFunc</code> inside of it.  (NB: this is not in a package, but in the global environment.)  I'd like to know where <code>localFunc</code> exists in the search path, as I'd like to analyze it via <code>mvbutils::foodweb</code>.</p>
  <p>Here is an example:</p>
  <pre><code>myFunc &lt;- function(){
      require(data.table)
      require(mvbutils)
      localFunc &lt;- function(x){
          return(as.data.table(x))
      }
      
      vecPrune &lt;- c(&quot;localFunc&quot;,ls(&quot;package:data.table&quot;))
      ix &lt;- match(&quot;data.table&quot;,search())
      tmpWeb &lt;- foodweb(where = c(1,ix), prune = vecPrune, plotting = FALSE)
      return(tmpWeb)
  }
  </code></pre>
  <p>However, a call to <code>myFunc()</code> does not seem to indicate that <code>localFunc</code> calls <code>data.table()</code>.  This is incorrect - what gives?</p>
  <p>(NB: The <code>where</code> argument specifies the search path.)</p>
  <hr />
  <p>Update 1: As Tommy and Spacedman point out, the trick is to specify <code>environment()</code>.  The call to <code>foodweb()</code> refers to <code>where = c(1, ix)</code>.  The index <code>1</code> is a mistake.  That arose from thinking that <code>.GlobalEnv</code>, which is often (always?) the first item in the <code>search()</code> vector, is the right place to search.  That is erroneous.  Instead, one should refer to <code>environment()</code>, and the correct call is below.  (NB: <code>ix</code> specifies the location of <code>data.table()</code> in the <code>search()</code> output.)</p>
  <pre><code>tmpWeb &lt;- foodweb(where = c(environment(),ix), prune = vecPrune, plotting = FALSE)
  </code></pre>
  <p>This appears in the answer to <a href="https://stackoverflow.com/a/8777882/805808">this question</a>, in a function called <code>checkScriptDependencies</code>, which wraps the code from an R script file into a local function, which is then analyzed by <code>foodweb</code>.  This is a limited example of how to use <code>environment()</code>, and Tommy has given a good explanation of how to use it and similar functions in this context.</p>