title: Finding cumulative product if a certain condition is met in R
body: <p>I have a dataset that looks like the following (called Data):</p>
  
  <pre><code>v1 v2
  1   1  
  1   3
  1   5
  2   3
  2   4
  3   1
  3   2
  </code></pre>
  
  <p>I want to return a vector v3 that:</p>
  
  <ul>
  <li>is equal to v2[i] if v1[i] is not equal to v1[i-1]</li>
  <li>is equal to v3[i-1]*v2[i] if v1[i] is equal to v1[i-1]</li>
  </ul>
  
  <p>So, in this example, v3 should return</p>
  
  <pre><code>v3
  1
  3
  15
  3
  12
  1
  2
  </code></pre>
  
  <p>I've lagged the column v1 by using lag.v1&lt;-c(NA,Data[1:nrow(Data)-1,1]) in order to compare to the previous row. I think something similar to the following should work, but with the value of v3 in the previous row instead of the current row.</p>
  
  <p>Data$v3&lt;-ifelse(1*(Data$v1==lag.v1)==1, Data$v3*Data$v2, Data$v2)</p>
  
  <p>In other words, I need to somehow access the previous row of v3 (lag v3) as I'm forming v3 in the above equation.</p>
  
  <p>Help is greatly appreciated, thank you!</p>