title: group by and find index of first non-zero in each group in data table
body: <p>I have a data table in R, that looks like:</p>
  
  <pre><code>   city year target
  1:  NYC 2000      0
  2:  NYC 2000      1
  3:  NYC 2000      1
  4:   LA 2000      0
  5:   LA 2000      0
  6:   LA 2000      1
  7:   LA 2000      1
  </code></pre>
  
  <p>which can be created by:</p>
  
  <pre><code>data = data.table(city = c("NYC", "NYC", "NYC", "LA", "LA", "LA", "LA"),
                    year = c(2000, 2000, 2000, 2000, 2000, 2000, 2000),
                    target = c(0, 1, 1, 0, 0, 1, 1))
  </code></pre>
  
  <p>I would like to group them by <code>city</code> and <code>year</code> and find index of the first nonzero element in column <code>target</code>so I can modify it, the desired result should look like:</p>
  
  <pre><code>   city year target
  1:  NYC 2000      0
  2:  NYC 2000    666
  3:  NYC 2000      1
  4:   LA 2000      0
  5:   LA 2000      0
  6:   LA 2000    666
  7:   LA 2000      1
  </code></pre>
  
  <p>any help is appreciated.</p>
  
  <p>The following does not work:</p>
  
  <pre><code>cutoff_thresh &lt;- function(x, cutoff) {x &gt; cutoff}
  
  helper &lt;- data %&gt;% 
            group_by(city, year) %&gt;%
            mutate(thresh = detect_index(.x = target,
                   .f = cutoff_thresh,
                    cutoff = 0)
                   )
  </code></pre>
  
  <p>It produces the exact day of a given year that the first non-zero element occurs,
  it starts counting at the first day of each year. So, if 2000 has 365 days in it, and the 2nd day of 2001 we is non-zero, it returns <code>2</code> for <code>(NYC, 2001)</code> as opposed to <code>365 + 2</code>. Not surprisingly!</p>