title: Select random consecutive rows by group as a proportion of group length
body: <p>Assuming I have a time series with different groups with various group length. How can I randomly select consecutive rows by group and as a function of each respective group length (e.g. 10 % of each group)</p>
  <p>I tried it by using <a href="https://stackoverflow.com/questions/52546036/select-two-random-and-consecutive-rows-from-grouped-data">code from here</a> - but it does not work with my data.</p>
  <pre><code>library(data.table)
  library(dplyr)
  
  # Creating a dummy dataframe:
  cell &lt;- c(rep(&quot;a&quot;, 100), rep(&quot;b&quot;, 80),  rep(&quot;c&quot;, 60),  rep(&quot;d&quot;, 40),  rep(&quot;e&quot;, 20), rep(&quot;f&quot;, 10))
  df &lt;- data.frame(cell) %&gt;% group_by(cell) %&gt;% mutate(Time = row_number()) %&gt;% as.data.table()
  
  df_subset &lt;- df[df[ , (sample(.I[-.N], 1)) + (0:(0.1*.N)), by = cell]$V1]
  </code></pre>
  <p>The issue with the subset:</p>
  <ul>
  <li>It does not take the proportion somehow as the amount of selected rows does not fully reflect the group length (I expect, 10,8,6,4,2 and 1 samples)</li>
  <li>A bigger issue is that for bigger proportions it actually samples outside of the length of each group. E.g. if it selects row 99 for a row length of 100, every random sampling above 2 creates NAs in my dataframe.</li>
  </ul>
  <p>I wrote my own function at the end - but I wonder if there is a nice dplyr or data.table way of handling this?</p>