title: How can I calculate difference between max and min over varying time series lengths in R?
body: <p>I have a timeseries of water depth measurements (15-min intervals) and I want to calculate the tidal height of each tidal cycle. Tidal height is the absolute difference between max depth and min depth for an outgoing tide (or vice versa for an incoming tide, hence the absolute difference). To complicate things, not all of my sites have 6-hour variations between high and low tides; some have more, some have less. I would like to have a way of calculating the absolute difference between max and min values that vary in the length of time between consecutive highs and lows.</p>
  <p>Just some random data:</p>
  <pre><code>dat &lt;- data.frame(matrix(vector(),20,2,
                           dimnames=list(c(), c(&quot;Time&quot;, &quot;Depth&quot;))),
                    stringsAsFactors = F)
  dat[,1] &lt;- seq(from = 1, to = 20, by = 1)
  dat[1:5,2] &lt;- seq(from = 0.5, to = 2.5, by = 0.5)
  dat[6:13,2] &lt;- seq(from = 2.6, to = 0.4, by = -0.28)
  dat[14:20,2] &lt;- seq(from = 0.4, to = 2.8, by = 0.4)
  </code></pre>
  <p>The output should have the following results:</p>
  <pre><code>    Tide TidalHeight
  1   1    2.1
  2   2    2.2
  3   3    2.4
  </code></pre>
  <p>Tide 1 would be the absolute difference between the low of 0.5 and high of 2.6, tide 2 would be the absolute difference between the high of 2.6 and low of 0.4, and tide 3 would be the absolute difference between the low of 0.4 and high of 2.8. The length of time between consecutive high and low tides varies, in the above example by 6, 8, and 6-time steps but in the real data this could be any number of time steps.</p>
  <p>I would like to know how to automatically calculate the absolute difference between high and low tides that vary in length of time between tides.</p>