title: Drop columns in a data.frame by sum of levels in R
body: <p>this problem is annoying because I'm searching for an answer this whole morning and I know that the answer must be very simple.</p>
  
  <p>I have a df with multiple factors or variables (more than in this example) and only two levels:</p>
  
  <pre><code>row.name  Factor1 Factor2 Factor3 Factor4
  1         dog     dog     cat     cat
  2         dog     dog     cat     dog
  3         dog     cat     dog     dog
  4         dog     cat     dog     dog
  </code></pre>
  
  <p>Now, I just want to drop these columns that contain <strong>dog</strong> and <strong>cat</strong> > 1</p>
  
  <pre><code>row.name  Factor2 Factor3
  1         dog     cat
  2         dog     cat
  3         cat     dog
  4         cat     dog
  </code></pre>
  
  <p>This must be very easy, but I can't find the right solution. I can already drop the columns that contain only one level but not those columns with two levels but with only one occurrence of one level.</p>
  
  <p>Any help is very appreciated.</p>
  
  <p>*edit</p>
  
  <p>Both approaches from Ryan worked for me after a slight change. The original solutions kept only the columns that contained only <strong>dog</strong>, e.g. Factor1</p>
  
  <pre><code>row.name  Factor1
  1         dog
  2         dog
  3         dog
  4         dog
  </code></pre>
  
  <p>Hence, I changed it in this way:</p>
  
  <pre><code>df %&gt;% 
    select_if(~ !is.factor(.x) | sum(tabulate(.x) &gt; 1) &gt;= 2)
  </code></pre>
  
  <p>and</p>
  
  <pre><code>df[, sapply(df, function(x) !is.factor(x) | sum(tabulate(x) &gt; 1) &gt;= 2)]
  </code></pre>
  
  <p>Both ways are working perfectly.</p>