title: How to merge between dates
body: <p>I have 2 dataframes that look like this:</p>
  
  <pre><code>df1
         ID   Drugname                    Startdate    Enddate     Dose   
        &lt;dbl&gt; &lt;chr&gt;                       &lt;date&gt;       &lt;date&gt;      &lt;chr&gt;    
  1   111xxx  LAMISIL CREME 10MG/G        2008-04-04  2008-04-12  2. DA   
  2   111xxx  LAMISIL CREME 10MG/G        2009-07-05  2009-07-12  2. AB   
  3   111xxx  LAMISIL CREME 5MG/G         2009-11-22  2009-12-05  2. AB   
  4   111xxx  TERBINAFINE TABL 250MG      2009-07-06  2009-08-11  1.1T    
  5   111xxx  CLOZAPINE TABL 25MG         2005-06-01  2005-06-28  N 2T    
  6   111xxx  CLOZAPINE TABL 25MG         2005-07-01  2005-07-28  N 2T    
  7   222xxx  MAGNESIUM HYD KAUWT 724MG   2000-04-11  2000-04-24  1.1T    
  8   222xxx  MAGNESIUM HYD KAUWT 724MG   2012-03-17  2012-03-25  1.1T    
  etc.
  </code></pre>
  
  <pre><code>df2
         ID    (...) DATE_RESULT v1    v2      
  1:   111xxx        2007-11-28  &lt;NA&gt;  165   
  2:   111xxx        2009-07-08  &lt;NA&gt;  105 
  3:   222xxx        2009-08-24  &lt;NA&gt;  125         
  4:   222xxx        2012-03-27    66  20       
  etc. 
  </code></pre>
  
  <p>I would like to merge <code>df1</code> and <code>df2</code> to  look like this:</p>
  
  <pre><code>       ID    (...) DATE_RESULT v1    v2   Drugname1 Drugname2   NearDrug
  1:   111xxx        2007-11-28  &lt;NA&gt;  165  NA        NA          NA
  2:   111xxx        2009-07-08  &lt;NA&gt;  105  LAMISIL   TERBINAFINE NA
  3:   222xxx        2009-08-24  &lt;NA&gt;  125  NA        NA          NA
  4:   222xxx        2012-03-27    66  20   NA        NA          MAGNESIUM
  etc. 
  
  </code></pre>
  
  <p>I would like to merge these by <code>ID</code> only when <code>DATE_RESULT</code> in <code>df2</code> falls between <code>Startdate</code> and <code>Enddate</code> in <code>df1</code>. As <code>ID</code>s can have multiple <code>Drugname</code>s, I would like them to be merged in the same row after each other as seen in row 2 of new df. </p>
  
  <p>Then I would like another merge/column (and I do not know if this is possible),  I would like to merge by <code>ID</code> only when <code>DATE_RESULT</code> in <code>df2</code> comes max 7 days after <code>Enddate</code> in <code>df1</code>, creating column <code>Neardrug</code>, as seen in row 4 of the new df.</p>
  
  <p>For the first issue I have tried this: <a href="https://stackoverflow.com/questions/49079412/r-merge-by-id-and-date-between-two-dates">r merge by id and date between two dates</a>, but that doesnt quite give me my desired new dataframe and im too rooky to alter that code. </p>
  
  <p>I would like to keep all data in <code>df2</code> and not <code>df1</code>.
  All information has been altered for obvious reasons.</p>