title: How to solve prcomp.default(): cannot rescale a constant/zero column to unit variance
body: <p>I have a data set of 9 samples (rows) with 51608 variables (columns) and I keep getting the error whenever I try to scale it:</p>
  
  <p>This works fine</p>
  
  <pre><code>pca = prcomp(pca_data)
  </code></pre>
  
  <p>However,</p>
  
  <pre><code>pca = prcomp(pca_data, scale = T)
  </code></pre>
  
  <p>gives</p>
  
  <pre><code>&gt; Error in prcomp.default(pca_data, center = T, scale = T) : 
    cannot rescale a constant/zero column to unit variance
  </code></pre>
  
  <p>Obviously it's a little hard to post a reproducible example. Any ideas what the deal could be?</p>
  
  <p>Looking for constant columns:</p>
  
  <pre><code>    sapply(1:ncol(pca_data), function(x){
                 length = unique(pca_data[, x]) %&gt;% length
               }) %&gt;% table
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>    .
          2     3     4     5     6     7     8     9 
       3892  4189  2124  1783  1622  2078  5179 30741 
  </code></pre>
  
  <p>So no constant columns. Same with NA's - </p>
  
  <pre><code>    is.na(pca_data) %&gt;% sum
  
      &gt;[1] 0
  </code></pre>
  
  <p>This works fine:</p>
  
  <pre><code>    pca_data = scale(pca_data)
  </code></pre>
  
  <p>But then afterwards both still give the exact same error:</p>
  
  <pre><code>    pca = prcomp(pca_data)
      pca = prcomp(pca_data, center = F, scale = F)
  </code></pre>
  
  <p>So why cant I manage to get a scaled pca on this data? Ok, lets make 100% sure that it's not constant.</p>
  
  <pre><code>    pca_data = pca_data + rnorm(nrow(pca_data) * ncol(pca_data))
  </code></pre>
  
  <p>Same errors. Numierc data?</p>
  
  <pre><code>    sapply( 1:nrow(pca_data), function(row){
        sapply(1:ncol(pca_data), function(column){
           !is.numeric(pca_data[row, column])
         })
       } ) %&gt;% sum
  </code></pre>
  
  <p>Still the same errors. I'm out of ideas. </p>
  
  <p>Edit: more and a hack at least to solve it.</p>
  
  <p>Later, still having a hard time clustering this data eg:</p>
  
  <pre><code>    Error in hclust(d, method = "ward.D") : 
        NaN dissimilarity value in intermediate results. 
  </code></pre>
  
  <p>Trimming values under a certain cuttoff eg &lt; 1 to zero had no effect. What finally worked was trimming all columns that had more than x zeros in the column. Worked for # zeros &lt;= 6, but 7+ gave errors. No idea if this means that this is a problem in general or if this just happened to catch a problematic column. Still would be happy to hear if anyone has any ideas why because this should work just fine as long as no variable is all zeros (or constant in another way).</p>