title: R: Random Sampling According to Some Constraint
body: <p>I am working with the R programming language. I have the following data:</p>
  <pre><code>set.seed(123)
  library(dplyr)
  
  id_sample &lt;- 1:25
  id &lt;- sample(id_sample, replace = TRUE, 100)
  var_1 = rnorm(100,100,100)
  var_2 = rnorm(100,100,100)
  var_3 = rnorm(100,100,100)
  
  data = data.frame(id, var_1, var_2, var_3)
  
  my_data =  data.frame(data %&gt;% group_by(id) %&gt;% mutate(index = row_number(id)))
  my_data &lt;- my_data[order(my_data$id),]
  
  groups = data.frame(my_data %&gt;% group_by(id) %&gt;% summarise(count=n()))
  
  final_data =  merge(x = my_data, y = groups, by = &quot;id&quot;, all.x = TRUE)
  </code></pre>
  <p>I want to randomly split this data into two datasets of 70%-30% (data_set_A, data_set_B), such that &quot;chronological order is preserved&quot;. By this I mean:</p>
  <ul>
  <li><p>Suppose id = 1 appears 5 times (id = (1,1,1,1,1), index = (1,2,3,4,5)) : data_set_A  could contain index(1,2) and data_set_b could contain (3,4,5)</p>
  </li>
  <li><p>But data_set_A could NOT contain index = (1,3,5) and data_set_B contain index (2,4)</p>
  </li>
  </ul>
  <p>I am not sure how to specify this constraint into the random sampling:</p>
  <pre><code>n &lt;- as.integer(length(final_data[,1])*0.7)
  data_70 &lt;- final_data[sample(nrow(final_data),n), ]
  data_30 &lt;- anti_join(final_data, data_70)
  </code></pre>
  <p><strong>Can someone please show me how to do this?</strong></p>
  <p>Thanks!</p>