title: Remove columns with standard deviation of zero
body: <p>I want to remove all columns with a standard deviation of zero from a data.frame.</p>
  
  <p>This does not work:</p>
  
  <pre><code>  df &lt;- df[, ! apply(df , 2 , function(x) sd(x)==0 ) ]
  </code></pre>
  
  <p>I get error:</p>
  
  <blockquote>
    <p>undefined columns selected</p>
  </blockquote>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I selected <code>Filter</code> as my preferred answer as it also seems to handle <code>NA</code>s, which is very useful.</p>
  
  <p>For example, in</p>
  
  <pre><code>df &lt;- data.frame(v1=c(0,0,NA,0,0), v2=1:5)
  </code></pre>
  
  <p>the column 'v1' is removed with <code>Filter</code> while the <code>apply</code> methods produce errors.</p>
  
  <p>Thanks to all the other solutions, I learned a lot from them.</p>
  
  <p><strong>UPDATE2:</strong></p>
  
  <p>Those errors given by apply can be fixed by adding <code>na.rm = TRUE</code> to the call to sd like so:</p>
  
  <pre><code>df[, ! apply(df , 2 , function(x) sd(x, na.rm = TRUE)==0 ) ]
  </code></pre>