title: Manipulating content of ellipsis in parent frame in R
body: <p>I am interested in manipulating the content of the ellipsis (<code>...</code>) in the parent frame of a function. In other words, I want to write a function that is able to manipulate the environment from which it is called. How can I do that (even though I know I shouldn't)?</p>
  
  <p><strong>Example:</strong></p>
  
  <p>I have an upper-level function <code>foo</code> which acts as a wrapper around a lower-level function <code>bar</code>. Among other tasks, it calls <code>bar</code> repeatedly. The function <code>foo</code> takes two arguments; one named <code>x</code>, the other named <code>y</code>, where <code>y</code> is part of the ellipsis. As a minimal example, imagine <code>foo</code> looks as follows.</p>
  
  <pre><code>foo &lt;- function(x,...){
    out &lt;- numeric(5)
    for(i in 1:5) out[i] &lt;- bar(x,...)
    return(out)
  }
  </code></pre>
  
  <p><strong>Note:</strong> I cannot change the content of <code>foo</code> because it's part of a large R package; I cannot, for example, unpack the ellipsis into something like <code>bar.args &lt;- list(...)</code> and manipulate it within <code>foo</code>. This makes it tricky.</p>
  
  <p>Inside <code>foo</code>, the lower-level function <code>bar</code> takes care of the actual computations. In addition (though not its sole purpose), it should be able to manipulate the content of the ellipsis in its parent frame, that is, it should receive limited control over <em>how</em> it is run when it is called multiple times. As a minimal example, <code>bar</code> might increase the value of <code>y</code> after each time it is called.</p>
  
  <pre><code>bar &lt;- function(...){
    ans &lt;- x + list(...)$y
    # change in parent frame: ...$y &lt;- ...$y + 1
    return(ans)
  }
  </code></pre>
  
  <p>Since the arguments of <code>bar</code> are contained in the ellipsis, I'm not aware of any nice and (relatively) safe way to do this. My own idea was to create a copy of <code>y</code> in the parent frame that I can easily access and modify.</p>
  
  <pre><code>bar &lt;- function(x,...){
  
    # check
    chk &lt;- mget("copyof.y", envir=parent.frame(), ifnotfound=NA)
  
    # change y or a copy of it
    if(is.na(chk$copyof.y)){
      ans &lt;- x + list(...)$y
      assign("copyof.y", list(...)$y+1, pos=parent.frame())
    }else{
      ans &lt;- x + chk$copyof.y
      assign("copyof.y", chk$copyof.y+1, pos=parent.frame())
    }
  
    return(ans)
  }
  
  # &gt; foo(1,y=1)
  # [1] 2 3 4 5 6
  </code></pre>
  
  <p>I realize, that this is "bad practice" in R because the closure of the function is being broken, thus pretty much nullifying what functions are usually for... However, I am not in control over <code>foo</code> and I can only change what <code>bar</code> is doing. In other words, I am trying to <em>trick</em> <code>foo</code> into allowing that <code>bar</code> has limited control over how it is run.</p>