Create a conditional count variable in R
<p>I want to create a count variable with the number of peoples with Z==0 in each of the given years. As Illustrated below: </p>

<pre><code>PersonID    Year    Z   Count*
       1    1990    0   1
       2    1990    1   1
       3    1990    1   1
       4    1990    2   1
       5    1990    1   1
       1    1991    1   3
       2    1991    0   3
       3    1991    1   3
       4    1991    0   3
       5    1991    0   3
       1    1992    NA  1
       2    1992    2   1
       3    1992    2   1
       4    1992    0   1
       5    1993    1   0
       1    1993    1   0
       2    1993    2   0
       3    1993    NA  0
       4    1993    1   0
       5    1994    0   5
       1    1994    0   5
       2    1994    0   5
       3    1994    0   5
       4    1994    0   5
</code></pre>

<p>I looked at my previous R-scripts and found this </p>

<pre><code>library(dplyr)
sum_data &lt;- data %&gt;% group_by(PersonID) %&gt;% summarise(Count = sum(Z, na.rm=T))
</code></pre>

<p>Can someone help me get this right? The count variable should basically count a total number of persons with Z==0, in the same format as I illustrated above. Thanks!!</p>

<pre><code>dput(data)
structure(list(PersonID = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L), 
    Year = c(1990L, 1990L, 1990L, 1990L, 1990L, 1991L, 1991L, 
    1991L, 1991L, 1991L, 1992L, 1992L, 1992L, 1992L, 1993L, 1993L, 
    1993L, 1993L, 1993L, 1994L, 1994L, 1994L, 1994L, 1994L), 
    Z = c(0L, 1L, 1L, 2L, 1L, 1L, 0L, 1L, 0L, 0L, NA, 2L, 2L, 
    0L, 1L, 1L, 2L, NA, 1L, 0L, 0L, 0L, 0L, 0L)), .Names = c("PersonID", 
"Year", "Z"), class = "data.frame", row.names = c(NA, -24L))
</code></pre>