title: Keep records into a dataframe based on another one using before and after dates
body: <p>Having this dataframe:</p>
  
  <pre><code>dframe1 &lt;- structure(list(id = c(1L, 1L, 1L, 2L, 2L), name = c("Google", 
  "Yahoo", "Amazon", "Amazon", "Google"), date = c("2008-11-01", 
  "2008-11-01", "2008-11-04", "2008-11-01", "2008-11-02")), class = "data.frame", row.names = c(NA, 
  -5L))
  </code></pre>
  
  <p>And this second one:</p>
  
  <pre><code>    dframe2 &lt;- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
  1L, 2L, 2L, 2L, 2L, 2L, 2L), date = c("2008-11-01", "2008-11-01", 
  "2008-11-04", "2008-10-31", "2008-10-31", "2008-11-02", "2008-11-02", 
  "2008-11-02", "2008-11-05", "2008-11-02", "2008-11-03", "2008-10-31", 
  "2008-11-01", "2008-11-01", "2008-11-02", "2008-11-02", "2008-11-03"
  ), name = c("Google", "Yahoo", "Amazon", "Google", "Yahoo", "Amazon", 
  "Google", "Yahoo", "Amazon", "Google", "Yahoo", "Amazon", "Google", 
  "Amazon", "Google", "Amazon", "Google"), text_sth = c("test", 
  "text_sth", "text here", "another text", "other", "another one", 
  "test", "text_sth", "text here", "another text", "other", "etc", 
  "test", "text_sth", "text here", "another text", "text here")), class = "data.frame", row.names = c(NA, 
  -17L))
  </code></pre>
  
  <p>Using the results of dframe1 how is it possible to keep from dataframe2 the rows which have the same name for every id as dframe1 but one date before and after the record date of dframe1?</p>
  
  <p>Here what I tried</p>
  
  <pre><code>library(data.table)
  library(tidyverse)
  library(reshape2)
  
  dframe1 = data.table(dframe1)
  dframe1[, date := as.Date(date)]
  
  dframe1_first = dframe1[, .(date = min(date)), .(id, name)] %&gt;% 
      mutate(date_pre = date - 1,
             date_after = date + 1)
  
  req_rows = dframe2 %&gt;%
      merge(dframe1_first %&gt;%
                rename(id = id),
            by = "id") %&gt;%
      filter(date &gt;= date_pre,
             date &lt;= date_after,
             date != date) %&gt;%
      mutate(period = ifelse(date&lt;date, '1-day-pre', '1-day-after'))
  </code></pre>
  
  <p>Expected output:</p>
  
  <blockquote>
  <pre><code> id       date   name     text_sth
  1 2008-10-31 Google another text
  1 2008-10-31  Yahoo        other
  1 2008-11-02 Google         test
  1 2008-11-02  Yahoo     text_sth
  1 2008-11-05 Amazon    text here
  1 2008-11-02 Google another text
  2 2008-10-31 Amazon          etc
  2 2008-11-01 Google         test
  2 2008-11-02 Amazon another text
  2 2008-11-03 Google    text here
  </code></pre>
  </blockquote>