title: How to easily create variable with number of group rows satisfying treatment condition?
body: <p>I have a grouped dataframe <code>df1</code>, and in a variable <code>n0</code> I want to count those cases in each group <code>id</code> which don't have the treatment <code>d</code>. First some data:</p>
  
  <p><strong>Data:</strong></p>
  
  <pre><code>set.seed(100)
  
  n &lt;- 1000
  
  df1 &lt;- data.frame(a=rbinom(n, 1, .5),
                    b=sample(20:40, n, replace = TRUE),
                    c=sample(seq(3000, 4000, 100), n, replace = TRUE),
                    d=rbinom(n, 1, .13),
                    k=rbinom(n, 1, .88),
                    l=rbinom(n, 1, .075),
                    m=rbinom(n, 1, .05),
                    n=rbinom(n, 1, .3))
  df1 &lt;- with(df1, df1[order(c, b, a),])
  df1$id &lt;- cumsum(!duplicated(df1[, c("a","b","c")]))
  df1$count &lt;- with(df1, ave(a, id, FUN=length))
  
  &gt; tail(df1, 6)
      a  b    c d k l m n  id count
  935 1 39 4000 0 1 0 0 1 407     4
  946 1 39 4000 0 1 0 0 1 407     4
  441 0 40 4000 0 1 0 1 0 408     1
  247 1 40 4000 1 1 0 0 0 409     3
  515 1 40 4000 0 1 0 0 0 409     3
  717 1 40 4000 0 1 1 0 1 409     3
  </code></pre>
  
  <p><strong>Attempt:</strong></p>
  
  <p>Here follows my attempt that seems quite cumbersome to me. Is there a shorter way to do this? Preferably staying in base R.</p>
  
  <pre><code>df1$n0 &lt;- unlist(sapply(1:length(unique(df1$id)), function(x) 
    with(df1, rep(nrow(df1[id == x &amp; d == 0, ]), 
                  nrow(df1[id == x, ])))))
  
  &gt; tail(df1, 6)
      a  b    c d k l m n  id count n0
  935 1 39 4000 0 1 0 0 1 407     4  4
  946 1 39 4000 0 1 0 0 1 407     4  4
  441 0 40 4000 0 1 0 1 0 408     1  1
  247 1 40 4000 1 1 0 0 0 409     3  2
  515 1 40 4000 0 1 0 0 0 409     3  2
  717 1 40 4000 0 1 1 0 1 409     3  2
  </code></pre>