title: Conditional grouping and summarizing data frame in [R]
body: <p>I have a data frame like this: </p>
  
  <pre><code>df &lt;- data.frame(ID = c("A", "A", "B", "B", "C", "C"), 
                   time = c(3.1,3.2,6.5,12.3, 3.2, 3.4), 
                   intensity = c(10, 20, 30, 40, 50, 60))
  </code></pre>
  
  <pre>
  |ID | time| intensity|
  |:--|----:|---------:|
  |A  |  3.1|        10|
  |A  |  3.2|        20|
  |B  |  6.5|        30|
  |B  | 12.3|        40|
  |C  |  3.2|        50|
  |C  |  3.4|        60|
  </pre>
  
  <p>I would like to aggregate values (sum intensities) by ID <em>only</em> when time difference is less than, i.e. 0.3. First I calculated this time difference: </p>
  
  <pre><code>df.2 &lt;- df %&gt;% 
          group_by(ID) %&gt;% 
          mutate(time.diff = max(time) - min(time)) 
  </code></pre>
  
  <p>...resulting in: </p>
  
  <pre>
  |ID | time| intensity| time.diff|
  |:--|----:|---------:|---------:|
  |A  |  3.1|        10|       0.1|
  |A  |  3.2|        20|       0.1|
  |B  |  6.5|        30|       5.8|
  |B  | 12.3|        40|       5.8|
  |C  |  3.2|        50|       0.2|
  |C  |  3.4|        60|       0.2|
  </pre>
  
  <p>Just to be clear, what I would like to get as an output would be:</p>
  
  <pre>
  |ID | time| intensity| time.diff|
  |:--|----:|---------:|---------:|
  |A  | 3.15|        30|       0.1|
  |B  |  6.5|        30|       5.8|
  |B  | 12.3|        40|       5.8|
  |C  |  3.3|       110|       0.2|
  </pre>
  
  <p>where time now is an average of the integrated observations, and intensity is the sum of them. The ID "B" keeps two observations, since its time difference is bigger than 0.3. I have tried with dplyr, but <em>summarise</em> will always drop one of the observations of "B", and I want to keep them, and I don't know how to do a <em>conditional</em> _group_by_. </p>
  
  <p>I thank you for any idea!!</p>