Count row with condition per group
<p>This code: </p>

<pre><code>Group &lt;- rep(c("A", "B", "C"), each = 3)
Days &lt;- c(21,21,19,18,21,21,11,21,19)
State &lt;- c("OK", "NOK", "OK", "OK", "NOK", "OK", "OK", "OK", "NOK")

data &lt;- data.frame(Group = Group, Days = Days, State = State)
</code></pre>

<p>create this data frame: </p>

<pre><code>&gt; data
  Group Days State
1     A   21    OK
2     A   21   NOK
3     A   19    OK
4     B   18    OK
5     B   21    OK
6     B   21    OK
7     C   11   NOK
8     C   21    OK
9     C   19   NOK
</code></pre>

<p>I often use <code>group_by</code> and <code>summarizes</code> of <code>dplyr</code> do get parameters of groups (eg. A, B, C). But I couldn't figure ou a simple way to get the amnount of OKs and NOKs per Group (eg. percentage NOK). The result I expect would by: </p>

<pre><code>  &gt; result
      Group   %NOK
    1     A   33.3
    2     B      0
    3     C   66.6 
</code></pre>

<p>In a further step I wish to count proportions with additional conitions. For example: Count the amount of NOKs, where days > 20 for every group. My really straightforward solution would be: </p>

<pre><code>data %&gt;% group_by(Group) %&gt;% nrow(filter(Days &lt; 20, State == "NOK")) / n() * 100
</code></pre>

<p>but it would be nice, if you could give my a solution, that is actually working ;) </p>