title: How can I create a new column in a dataframe based on subset of the same data
body: <p>Sorry if this is a dumb question, I'm new to R.
  I have a data set like this:</p>
  
  <pre><code>   t a b
  1  1 1 0
  2  2 1 0
  3  3 1 4
  4  4 1 0
  5  5 1 2
  6  1 2 0
  7  2 2 1
  8  3 2 3
  9  4 2 0
  10 5 2 5
  </code></pre>
  
  <p>I want to add a new column <code>c</code> which is on if <code>b</code> is zero and no previous <code>b</code> grouped by <code>a</code> was not zero, and zero if not. Basically I want to mark the leading zeros for each <code>a</code>, based on the <code>t</code> index. The result should look like this:</p>
  
  <pre><code>   t a b c
  1  1 1 0 1
  2  2 1 0 1
  3  3 1 4 0
  4  4 1 0 0
  5  5 1 2 0
  6  1 2 0 1
  7  2 2 1 0
  8  3 2 3 0
  9  4 2 0 0
  10 5 2 5 0
  </code></pre>
  
  <p>I tried running </p>
  
  <pre><code>data.c &lt;- ifelse(nrow(subset(data, t &lt; data$t &amp; a == data$a &amp; b != 0)) == 0 &amp; data$b == 0, 1, 0)
  </code></pre>
  
  <p>but that just set <code>c</code> to 1 if <code>b</code> was 0. What am I doing wrong? How would you approach this?
  Thanks</p>
  
  <p><strong>Reproducible example:</strong></p>
  
  <pre><code>t &lt;- "time a b 
  1 1 1 0
  2 2 1 0
  3 3 1 4
  4 4 1 0
  5 5 1 2
  6 1 2 0
  7 2 2 3
  8 4 2 5
  9 4 2 0"
  
  data &lt;- read.table(text=t, header = TRUE)
  
  data$c &lt;- ifelse(nrow(subset(data, t &lt; data$t &amp; a == data$a &amp; b != 0)) == 0 &amp; data$b == 0, 1, 0)
  </code></pre>