title: Calculate the proportion of values every two rows by group in R
body: <p>I have this dataset</p>
  <pre><code>
  
  df &lt;- tibble(id, event, duration)
  </code></pre>
  <p>I need that the each &quot;dive&quot; row the duration proportion of surface be calculated using the subsequent &quot;surface&quot;, and insert the result into a new column. All this separated by &quot;id&quot;.</p>
  <p>proportion = surface/dive+surface</p>
  <pre><code>#Output dataframe
  
  # A tibble: 8 x 4
    id    event   duration proportion    
  1 A     surface       56 x         
  2 A     surface       96 x         
  3 A     surface       14 x         
  4 A     surface       77 x         
  5 B     surface       28 x         
  6 B     surface       63 x         
  7 B     surface       47 x         
  8 B     surface       90 x   
  
  ############################################################
  </code></pre>
  <p><strong>Edit:</strong></p>
  <p>In my original data, i have some &quot;dive&quot; without &quot;surface&quot; and this code created is with error.</p>
  <pre><code>Error in `dplyr::mutate()`:
  ! Problem while computing `proportion = DurationMin[What ==
    &quot;Surface&quot;]/sum(DurationMin)`.
  ✖ `proportion` must be size 2 or 1, not 0.
  ℹ The error occurred in group 2803: ptt = &quot;2017111870&quot;, grp = 1015.
  </code></pre>
  <p>Inside an 'id' there will be an odd number of rows, where a &quot;dive&quot; event will not have a &quot;surface&quot; in its sequence. So I need that every time an unpaired event is encountered, it is either ignored or an NA is inserted. It's possible?</p>
  <p>Follow this dataframe example:</p>
  <pre><code>
  id &lt;- c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;)
  
  event &lt;- c(&quot;dive&quot;, &quot;surface&quot;, &quot;dive&quot;, &quot;surface&quot;, &quot;dive&quot;, &quot;surface&quot;, &quot;dive&quot;, &quot;surface&quot;, &quot;dive&quot;, &quot;surface&quot;, &quot;dive&quot;, &quot;surface&quot;, &quot;dive&quot;, &quot;surface&quot;, &quot;dive&quot;)
  
  duration &lt;- c(55, 56, 40, 96, 58, 14, 43, 77, 19, 28, 34, 63, 29, 47, 61)
  
  df &lt;- tibble(id, event, duration)
  
  &gt; df
     id   event duration
  1   A    dive       55
  2   A surface       56
  3   A    dive       40
  4   A surface       96
  5   A    dive       58
  6   A surface       14
  7   A    dive       43
  8   A surface       77
  9   B    dive       19
  10  B surface       28
  11  B    dive       34
  12  B surface       63
  13  B    dive       29
  14  B surface       47
  15  B    dive       61
  16  B    dive       45
  17  B surface       30
  &gt; 
  </code></pre>