title: dtplyr throws an 'invalid 'type' (closure) of argument' using group_by() %>% sample_n() in dplyr and [[sample()], by=id] in data.table
body: <p>I've been using <code>dtplyr</code> to speed up an overly complex <code>dplyr</code> code, and so far it's been excellent, apart from one issue I can't seem to resolve.</p>
  <p>The problem is pretty straight forward to solve in both <code>dplyr</code> and <code>data.table</code>, but I can't see a way of applying it to a <code>dtplyr_step</code> object from <code>lazy_dt()</code> without using <code>collect()</code> or converting it back to a <code>data.frame</code>.</p>
  <p>I'm trying to group a dataframe by one column, and sample rows n times based on values in another column.<br />
  Here's a working example in <code>dplyr</code>:</p>
  <pre><code>library(dplyr)
  
  df &lt;- data.frame(id=c(&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;,&quot;d&quot;,&quot;d&quot;,&quot;d&quot;), 
                   count=sample(1:25, 12, replace=TRUE))
  
  df %&gt;% group_by(id) %&gt;% sample_n(max(count), replace = TRUE)
  </code></pre>
  <p>and in <code>data.table</code>:</p>
  <pre><code>library(data.table)
  
  dt &lt;- data.table(id=c(&quot;a&quot;,&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;,&quot;d&quot;,&quot;d&quot;,&quot;d&quot;), 
                   count=sample(1:25, 12, replace=TRUE))
  
  dt[,.SD[sample(.N, max(count,.N), replace=TRUE)],by = id]
  
  </code></pre>
  <p>However, attempting both approaches used on an identical &quot;lazy&quot; <code>data.table</code> created  with <code>lazy_dt()</code> from the <code>dtplyr</code> package:</p>
  <pre><code>library(dtplyr)
  
  df2 &lt;- lazy_dt(df)
  
  df2 %&gt;% group_by(id) %&gt;% sample_n(max(count), replace = TRUE)
  </code></pre>
  <p>fails with <em>Error in max(count) : invalid 'type' (closure) of argument</em></p>
  <pre><code>df2[,.SD[sample(.N, max(count,.N), replace=TRUE)],by = id]
  </code></pre>
  <p>fails with <em>Error in max(count, .N) : invalid 'type' (closure) of argument</em></p>
  <p>Presumably because the <code>count</code> column is no longer recognised as numeric.</p>
  <p>Is there a way of doing this in <code>dtplyr</code> <strong>without</strong> converting this back to a data.frame or <code>data.table</code> (other than recoding the original <code>dplyr</code> code to <code>data.table</code> entirely?)</p>