title: Summarise data sacrificing the least resolution (creating groups of varying size based on a sum of lagged values)
body: <p>Given a table with separate measures for different time points, I would like to summarise the table, based on the sum of values in column <code>measurement</code> of the current and previous time points. I would like to do this for every group of time points, where the sum of current + previous <code>measurement</code>s is below a certain threshold. Any row where <code>measurement</code> is above the cutoff should not be summarised.</p>
  
  <p>Caveat: if the sum of two successive <code>measurement</code>s is above the threshold, but the next measurement is still below, it should be added to the next row.</p>
  
  <p>Here is an example table:</p>
  
  <pre><code>d &lt;- data.frame(name = c(rep("A", 8), rep("B", 8), rep("C", 8), rep("D", 8)),
                  time = c(rep(c(1:8),4)),
                  measurement = c(NA, 7, 17, 18, 30, 28, 24, 21,
                                  1, 2, 3, 5, 18, 15, 38, 39,
                                  11, 23, 67, 94, 405, 830, 1550, 2020,
                                  25, 60, 200, 300, 1100, 2200, 3000, 3500))
  </code></pre>
  
  <p>I've tried introducing a column that I can use to <code>group_by</code> and then <code>summarise</code>, by using the sum of the current <code>measurement</code>, <code>lag(measurement, order_by = time)</code> and <code>lag(measurement, n = 2, order_by = time)</code> and asking if the sum of is above a threshold (eg. <code>20</code>). It's easy to see that this is pretty static and clumsy, though.</p>
  
  <p>Also, in doing so, my initial test resulted in <code>name == A</code> being summarised, and all others are not.</p>
  
  <p>What I'd like to achieve is:</p>
  
  <pre><code>   name time measurement
  1     A    3          24
  2     A    5          48
  3     A    6          28
  4     A    7          24
  5     A    8          21
  6     B    5          29
  7     B    7          53
  8     B    8          39
  9     C    2          34
  10    C    3          67
  11    C    4          94
  12    C    5         405
  13    C    6         830
  14    C    7        1550
  15    C    8        2020
  16    D    1          25
  17    D    2          60
  18    D    3         200
  19    D    4         300
  20    D    5        1100
  21    D    6        2200
  22    D    7        3000
  23    D    8        3500
  </code></pre>