title: Generate a new variable based upon the values of the previous and next row by group
body: <p>I am using panel data with multiple subjects (<code>id</code>) and have an event (<code>first_occurrence</code>) that occurs on different days.  My goal is to create a new variable (<code>result</code>) that is 1 on the 2 days preceding the <code>first occurrence</code>, the day of the <code>first occurrence</code>, and the 2 days following the <code>first occurrence</code>.</p>
  
  <p>Here is an example that includes both the sample data and the desired output:</p>
  
  <pre><code>data &lt;- structure(list(id = c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 
  2, 3, 3, 3, 3, 3, 3, 3), day = c(0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 
  2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6), first_occurrence = c(0, 0, 
  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1), desired_output = c(1, 
  1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1)), .Names = c("id", 
  "day", "first_occurrence", "desired_output"), row.names = c(NA, 
  -21L), class = "data.frame")
  </code></pre>
  
  <p>Although this may not be the most efficient solution, I managed to get the code working in Stata (please see below for Stata code), although I would like to get it working in R as well and would appreciate any thoughts folks have.</p>
  
  <p>Thanks!</p>
  
  <p>Stata code:</p>
  
  <pre><code>tsset id day
      gen run = .
          by id: replace run = cond(L.run == ., 1, L.run + 1)
  
  gen test = .
      replace test = run if(first_occurrence == 1)
  
  gen test2 = .
      by id: replace test2 = test[_n-1]
  gen test3 = .
       by id: replace test3 = test[_n-2]
  gen test4 = .
      by id: replace test4 = test[_n+1]
  gen test5 = .
      by id: replace test5 = test[_n+2]
  
  egen test_sum = rowtotal(test test2 test3 test4 test5)
  replace test_sum = 1 if(test_sum &gt;= 1)
      rename test_sum result
  
  drop run test test2 test3 test4 test5
  </code></pre>