title: variables not recognized in for-loop nested within lapply
body: <p>I have the following data </p>
  
  <pre><code>set.seed(42)
  dat &lt;- list(data.table(id=1:10, group=rep(1:2, each=5), x=rnorm(10)), 
              data.table(id=1:10, group=rep(1:2, each=5), x=rnorm(10)))
  </code></pre>
  
  <p>to which I would like to apply this function element by element and group by group.</p>
  
  <pre><code>subs = function(x, ..., verbose=FALSE){
    L   = substitute(list(...))[-1]
    mon = data.table(cond = as.character(L))[, skip := FALSE]
  
    for (i in seq_along(L)){
      d = eval( substitute(x[cond, verbose=v], list(cond = L[[i]], v = verbose)) )
      if (nrow(d)){
        x = d
      } else {
        mon[i, skip := TRUE]
      }    
    }
    #print(mon)
    return(x)
  }
  </code></pre>
  
  <p>However, when I run this code</p>
  
  <pre><code># works
  out &lt;- lapply(1:2, function(h){
      res &lt;- list()
      d &lt;- dat[[h]] 
      for(k in 1:2){
          g &lt;- d[group==k]
          cutoff &lt;- 1
          print(cutoff)
          res[[k]] &lt;- subs(g, x&gt;cutoff)
      }
      res
  })
  </code></pre>
  
  <p>I receive the error that object <code>cutoff</code> cannot be found, although it is printed correctly. However, when I apply the same for-loop outside of the <code>lapply()</code>, it appears to work. </p>
  
  <pre><code>d1 &lt;- dat[[1]]
  s &lt;- list()
  for(k in 1:2){
      g &lt;- d1[group==k]
      cutoff &lt;- 1
      s[[k]] &lt;- subs(g, x&gt;cutoff)
  }
  
  &gt; s
  [[1]]
     id group        x
  1:  1     1 1.370958
  
  [[2]]
     id group        x
  1:  7     2 1.511522
  2:  9     2 2.018424
  </code></pre>
  
  <p>This leads me to suspect that it's the inclusion in the <code>lapply()</code> that causes the error but I find it hard to see what the error is, let along how to fix it. </p>
  
  <p><strong>Edit</strong></p>
  
  <p>Data with two variables:</p>
  
  <pre><code>set.seed(42)
  dat &lt;- list(data.table(id=1:10, group=rep(1:2, each=5), x=rnorm(10), y=11:20), 
              data.table(id=1:10, group=rep(1:2, each=5), x=rnorm(10), y=11:20))
  </code></pre>
  
  <p>with expected result</p>
  
  <pre><code>[[1]]
     id group          x   y
  1:  9     2  2.0184237  19
  2:  1     1  1.3709584  11
  3:  2     1 -0.5646982  12
  4:  3     1  0.3631284  13
  5:  4     1  0.6328626  14
  6:  5     1  0.4042683  15
  
  [[2]]
     id group          x   y
  1:  2     1  2.2866454  12
  2: 10     2  1.3201133  20
  </code></pre>