title: Forming a new variable based on previous row value
body: <p>My data is of the following form</p>
  
  <pre><code>structure(list(Flag = c(1, 0, 0, 1, 0, 0, 1, 0), variable = c(3, 
  8, 6, 7, 1, 4, 3, 6), sale = c(26, 27, 61, 38, 79, 87, 81, 13
  )), .Names = c("Flag", "variable", "sale"), row.names = c(NA, 
  -8L), class = "data.frame")
  </code></pre>
  
  <p>And I want to create output as follows</p>
  
  <pre><code>structure(list(Flag = c(1, 0, 0, 1, 0, 0, 1, 0), variable = c(3, 
  8, 6, 7, 1, 4, 3, 6), sale = c(26, 27, 61, 38, 79, 87, 81, 13
  ), begin = c(3, -23, -50, 7, -31, -70, 3, -78), end = c(-23, 
  -50, -111, -31, -70, -151, -78, -91)), .Names = c("Flag", "variable", 
  "sale", "begin", "end"), row.names = c(NA, -8L), class = "data.frame")
  </code></pre>
  
  <p>where the ne column begin and end are based on the following algorathim</p>
  
  <pre><code>if flag=1 then 
      begin=variable;
      end=variable-sale;
  ----------
  else
  begin=lag(end) ( i.e the previous value of end variable)
  end= lag(end)-sale
  </code></pre>
  
  <p>What I want is when flag is 1 the value of "begin" is equalt to "variable" value  and "end" value is "variable-sale" value.
  Where as for the others the value of begin is the previous row "end" value and "end" value is (begin-sales) value
  Can anyone help me how to write achieve this in R?</p>