title: Find the maximum in a certain time frame in a non-continuous time series
body: <p>I have a dataframe with a time series that looks like this:</p>
  
  <pre><code>df&lt;-structure(list(date = structure(c(-6905, -6891, -6853, -6588, 
  -6588, -6586, -6523, -6515, -5856, -5753), class = "Date"), flow = c(2.22, 
  2.56, 3.3, 1.38, 4, 1.4, 1.32, 1.26, 6, 35.69)), .Names = c("date", 
  "flow"), row.names = c(NA, 10L), class = "data.frame")
  </code></pre>
  
  <p>I want to remove all the lines that are not the maximum within 2 days forward or backward of its date. So in the case above, lines 4 and 6 will be removed. I couldn't find similar answered questions.</p>
  
  <p>I wrote this code that doesn't work and it is ugly, long and doesn't take care of the edges of the dataframe:</p>
  
  <pre><code>  idx &lt;- c()
    for (j in 3:(length(df$date)-2)){
      if (as.Date(df$date[j+2])-as.Date(df$date[j])&lt;3 |
          as.Date(df$date[j])-as.Date(df$date[j-2])&lt;3){
        if (df$flow[j]!=max(df$flow[(j-2):(j+2)])){
          idx &lt;- c(idx,j)
        }
      } else if (as.Date(df$date[j+1])-as.Date(df$date[j])&lt;3 |
                 as.Date(df$date[j])-as.Date(df$date[j-1])&lt;3){
        if (df$flow[j]!=max(df$flow[(j-1):(j+1)])){
          idx &lt;- c(idx,j)
        }
      }
    }
  </code></pre>
  
  <p>Notice that the dates in the dataframe are not consecutive.</p>