title: How to flag the last row of a data frame group?
body: <p>Suppose we start with the below dataframe <code>df</code>:</p>
  <pre><code> ID &lt;- c(1, 1, 1, 5, 5)
   Period &lt;- c(1,2,3,1,2)
   Value &lt;- c(10,12,11,4,6)
   df &lt;- data.frame(ID, Period, Value)
  
        ID Period Value
      1  1      1    10
      2  1      2    12
      3  1      3    11
      4  5      1     4
      5  5      2     6
  </code></pre>
  <p>Now using dplyr I add a &quot;Calculate&quot; column that multiplies Period and Value of each row, giving me the following:</p>
  <pre><code>&gt; df %&gt;% mutate(Calculate = Period * Value)
  
    ID Period Value Calculate
  1  1      1    10        10
  2  1      2    12        24
  3  1      3    11        33
  4  5      1     4         4
  5  5      2     6        12
  </code></pre>
  <p>I'd like to modify the above &quot;Calculate&quot; to give me a value of 0, when reaching the last row for a given ID, so that the data frame output looks like:</p>
  <pre><code>  ID Period Value Calculate
  1  1      1    10        10
  2  1      2    12        24
  3  1      3    11         0
  4  5      1     4         4
  5  5      2     6         0
  </code></pre>
  <p>I was going to use the <code>lead()</code> function to peer at the next row to see if the ID changes but wasn't sure that happens when reaching the end of the data frame.</p>
  <p>How could this be accomplished using dplyr?</p>