title: R- random sample of groups in a data.table
body: <p>How can I randomly sample e.g. three groups within a data.table so that the result contains three groups with all rows from the original data.table? </p>
  
  <pre><code>library(data.table)
  dat &lt;- data.table(ids=1:20, groups=sample(x=c("A","B","C", "D", "E", "F"), 20, 
  replace=TRUE))
  </code></pre>
  
  <p>I know how to select 10 rows randomly from a data.table:</p>
  
  <pre><code>dat.sampl1 &lt;- as.data.table(sapply(dat[], sample, 10))
  </code></pre>
  
  <p>And also how to sample by group </p>
  
  <pre><code>dat[,.SD[sample(.N, min(.N,3))], by = groups]
  </code></pre>
  
  <p>But how to randomly sample groups? So the result should look like:</p>
  
  <pre><code>    ids groups
       1      F
      11      F
       3      F
      18      F
       8      A
       9      A
      10      A
      17      A
      19      A
      12      E
      14      E
      16      E
  </code></pre>