title: Select rows of data frame based on a vector with duplicated values
body: <p>What I want can be described as: give a data frame, contains all the case-control pairs. In the following example, y is the id for the case-control pair. There are 3 pairs in my data set. I'm doing a resampling with respect to the different values of y (the pair will be both selected or neither). </p>
  
  <pre><code>sample_df = data.frame(x=1:6, y=c(1,1,2,2,3,3))
  &gt; sample_df
    x y
  1 1 1
  2 2 1
  3 3 2
  4 4 2
  5 5 3
  6 6 3
  select_y = c(1,3,3)
  select_y
  &gt; select_y
  [1] 1 3 3
  </code></pre>
  
  <p>Now, I have computed a vector contains the pairs I want to resample, which is <code>select_y</code> above. It means the case-control pair number 1 will be in my new sample, and number 3 will also be in my new sample, but it will occur 2 times since there are two 3. The desired output will be:</p>
  
  <pre><code>x y
  1 1
  2 1
  5 3
  6 3
  5 3
  6 3
  </code></pre>
  
  <p>I can't find out an efficient way other than writing a for loop...</p>
  
  <p>Solution:
  Based on @HubertL , with some modifications, a 'vectorized' approach looks like:</p>
  
  <pre><code>sel_y &lt;- as.data.frame(table(select_y))
  &gt; sel_y
    select_y Freq
  1        1    1
  2        3    2
  sub_sample_df = sample_df[sample_df$y%in%select_y,]
  &gt; sub_sample_df
    x y
  1 1 1
  2 2 1
  5 5 3
  6 6 3
  match_freq = sel_y[match(sub_sample_df$y, sel_y$select_y),]
  &gt; match_freq
      select_y Freq
  1          1    1
  1.1        1    1
  2          3    2
  2.1        3    2
  sub_sample_df$Freq = match_freq$Freq
  rownames(sub_sample_df) = NULL
  sub_sample_df
  &gt; sub_sample_df
    x y Freq
  1 1 1    1
  2 2 1    1
  3 5 3    2
  4 6 3    2
  selected_rows = rep(1:nrow(sub_sample_df), sub_sample_df$Freq)
  &gt; selected_rows
  [1] 1 2 3 3 4 4
  sub_sample_df[selected_rows,]
      x y Freq
  1   1 1    1
  2   2 1    1
  3   5 3    2
  3.1 5 3    2
  4   6 3    2
  4.1 6 3    2
  </code></pre>