title: Sample n random rows per group in a dataframe
body: <p>From these questions - <a href="https://stackoverflow.com/questions/9628152/random-sample-of-rows-from-subset-of-an-r-dataframe">Random sample of rows from subset of an R dataframe</a>  &amp;  <a href="https://stackoverflow.com/questions/8273313/random-rows-in-dataframe-in-r">Sample random rows in dataframe</a>  I can easily see how to randomly sample (select) 'n' rows from a df, or 'n' rows that originate from a specific level of a factor within a df.</p>
  
  <p>Here are some sample data:</p>
  
  <pre><code>df &lt;- data.frame(matrix(rnorm(80), nrow=40))
  df$color &lt;-  rep(c("blue", "red", "yellow", "pink"), each=10)
  
  df[sample(nrow(df), 3), ] #samples 3 random rows from df, without replacement.
  </code></pre>
  
  <p>To e.g. just sample 3 random rows from 'pink' color - using <code>library(kimisc)</code>:</p>
  
  <pre><code>library(kimisc)
  sample.rows(subset(df, color == "pink"), 3)
  </code></pre>
  
  <p>or writing custom function:</p>
  
  <pre><code>sample.df &lt;- function(df, n) df[sample(nrow(df), n), , drop = FALSE]
  sample.df(subset(df, color == "pink"), 3)
  </code></pre>
  
  <p>However, I want to sample 3 (or n) random rows from <em>each level</em> of the factor. I.e. the new df would have 12 rows (3 from blue, 3 from red, 3 from yellow, 3 from pink). It's obviously possible to run this several times, create newdfs for each color, and then bind them together, but I am looking for a simpler solution.</p>