title: R - dplyr - filter top_n rows based on multiple conditions
body: <h1>Hi, this is my first post,</h1>
  
  <p>I hope to get it right and reproducible.</p>
  
  <p>I was wondering if there is a more elegant solution than my approach below</p>
  
  <p>I have a dataframe and would like to use conditional filters and extract rows that meet these conditions. </p>
  
  <p><strong>As output I would like the top_n rows that meet the conditional criteria (different conditions for top_n output from different columns), whilst preserving all other columns.</strong></p>
  
  <p>Example dataframe:</p>
  
  <pre><code> set.seed(123)
    df1 &lt;- data.frame(
    A = as.numeric(1:10),
    B = sample(seq(as.Date('2000/01/01'), as.Date('2018/01/01'), by="day"), size=10),
    C = as.numeric(sample(20:90, size = 10)),
    D = sample(c("yes", "no"), size=10, replace = TRUE),
    E = as.numeric(sample(1000:2000, size = 10))
  )
  
  
  df1 #check output
  
  &gt; df1 #check output
      A          B  C   D    E
  1   1 2005-03-06 87  no 1963
  2   2 2014-03-11 51  no 1902
  3   3 2007-05-12 66  no 1690
  4   4 2015-11-22 58  no 1793
  5   5 2016-12-02 26  no 1024
  6   6 2000-10-26 79  no 1475
  7   7 2009-07-01 35  no 1754
  8   8 2016-01-19 22  no 1215
  9   9 2009-11-30 40 yes 1315
  10 10 2008-03-17 85 yes 1229
  </code></pre>
  
  <p><strong>Conditions I would like to use for filtering:</strong></p>
  
  <p>A) if column E is between 1000 and 1500 return top 2 rows weighted on column A</p>
  
  <p>B) if column E is between 1000 and 2000 return top 2 rows weighted on column B</p>
  
  <p>C) if column E is between 1000 and 1400 return top 2 rows weighted on column C</p>
  
  <p>I have come up with the following solution but it is cumbersome and I wondered if there is a better approach. </p>
  
  <pre><code>library("dplyr")
  library("tidyr")
  A&lt;- df1 %&gt;% dplyr::filter(E &gt;= 1000 &amp; E &lt;= 1500) %&gt;% top_n( n = 2, wt = A)  %&gt;% arrange(-A) %&gt;% mutate(condition = "-cond_A")
  B&lt;- df1 %&gt;% dplyr::filter(E &gt;= 1000 &amp; E &lt;= 2000) %&gt;% top_n( n = 2, wt = B) %&gt;% arrange(B) %&gt;% mutate(condition = "cond_B")
  C&lt;- df1 %&gt;% dplyr::filter(E &gt;= 1000 &amp; E &lt;= 1400) %&gt;% top_n( n = 2, wt = C) %&gt;% arrange(-C) %&gt;% mutate(condition = "-cond_C")
  </code></pre>
  
  <p>my desired output is the following:</p>
  
  <pre><code>spread(as.data.frame(distinct(bind_rows(A,B,C))),condition, condition)
  
     A          B  C   D    E -cond_A -cond_C cond_B
  1  5 2016-12-02 26  no 1024    &lt;NA&gt;    &lt;NA&gt; cond_B
  2  8 2016-01-19 22  no 1215    &lt;NA&gt;    &lt;NA&gt; cond_B
  3  9 2009-11-30 40 yes 1315 -cond_A -cond_C   &lt;NA&gt;
  4 10 2008-03-17 85 yes 1229 -cond_A -cond_C   &lt;NA&gt;
  </code></pre>
  
  <h1>Would be great if you could tell me a better approach!</h1>