title: Apply a for loop by group in a dataframe
body: <p>I have a dataframe called (df) with the following structure:</p>
  
  <pre><code>day colA colB
  1   4    8
  2   9    2
  3   8    1
  4   9    4 
  1   5    8
  2   2    4
  </code></pre>
  
  <p><strong>Problem:</strong></p>
  
  <p>I want to create a new column called 'colC' with the following logic:</p>
  
  <pre><code>if day is equal to 1, then colC = colA+colB
  if day not equal to 1, then colC = (colA+colB) - previous ColC 
  </code></pre>
  
  <p><strong>Expected solution:</strong></p>
  
  <pre><code>day colA colB colC
  1   4    8    12
  2   9    2    -1
  3   8    1    10
  4   9    4    3 
  1   5    8    13
  2   2    4    -7
  </code></pre>
  
  <p><strong>Current Solution:</strong></p>
  
  <pre><code>for(i in 1:NROW(df)
  {
  if(day[i] == 1) {colC[i] &lt;- colA[i] + colB[i]} 
  else {colC[i] &lt;- colA[i] + colB[i] - colC[i-1]}  
  }
  </code></pre>
  
  <p><strong>Issue:</strong></p>
  
  <ul>
  <li>The size of the dataset is too large hence, for loop is tremendously
  slow</li>
  <li>In my dataset the day column as values till day 7</li>
  <li>Basically I am looking for a solution where dataset can be split and for loop can be applied independently for each subset (assume each continous day 1-4 are one group)</li>
  </ul>