R data frame subsetting based on a column value frequency threshold
<p>I am a new R user and this is my first question submission (hopefully in compliance with the protocol). </p>

<p>I have a data frame with two columns.</p>

<pre><code>df &lt;- data.frame(v1 = c("A", "A", "B", "B", "B", "B", "C", "D", "D", "E" )) 
dfc &lt;- df %&gt;% count(v1)
df$n &lt;- with(dfc, n[match(df$v1,v1)])

   v1 n  
1   A 2
2   A 2
3   B 4
4   B 4
5   B 4
6   B 4
7   C 1
8   D 2
9   D 2
10  E 1
</code></pre>

<p>I want to delete rows that exceed a threshold of 3 occurrences for a value in v1.  All rows for that value less than the threshold are retained.  In this example I want to delete row 6 and retain all remaining rows in a subset data frame. </p>

<p>The result would include the following values for v1: </p>

<pre><code>  v1
1  A
2  A
3  B
4  B
5  B
6  C
7  D
8  D
9  E
</code></pre>

<p>Row 6 would have been deleted because it was the 4th occurrence of "B", but the 3 previous rows for "B" have been retained.</p>

<p>I have read multiple posts that demonstrate how to remove ALL rows for a variable with row totals less/greater than a cumulative frequency value, such as 4. For example, I have tried:</p>

<pre><code>df1 &lt;- df %&gt;%
  group_by(v1) %&gt;%
  filter(n() &lt; 4)
</code></pre>

<p>This approach keeps only the rows where all unique occurrences of V1 are &lt; 4.  6 rows are subset.</p>

<pre><code>df2 &lt;- df %&gt;%
  group_by(v1) %&gt;%
  filter(n() &gt; 3)
</code></pre>

<p>This approach keeps only the rows where all unique occurrences of v1 are > 3.  4 rows are subset.</p>

<pre><code>df4 &lt;- subset(df, v1 %in% names(table(df$v1))[table(df$v1) &lt;4])
</code></pre>

<p>This approach has the same result as the first approach.</p>

<p>None of these methods produce the result I need.  </p>

<p>As previously stated, I need to retain the first three rows where v1="B" and only delete rows if there are > 3 occurrences of that value. </p>

<p>Because I am new to R, it's possible I am overlooking a very simple solution.  Any suggestions would be greatly appreciated.  </p>

<p>Thanks.</p>