title: Downsample matrix in R?
body: <p>My question is about how to improve the performance of function that downsamples from the columns of a matrix without replacement (a.k.a. "rarefication" of a matrix... I know there has been mention of this <a href="https://stat.ethz.ch/pipermail/r-help/2006-October/114813.html" rel="nofollow">here</a>, but I could not find a clear answer that a) does what I need; b) does it quickly).  </p>
  
  <p>Here is my function:</p>
  
  <pre><code>downsampled &lt;- function(data,samplerate=0.8) {
      data.test &lt;- apply(data,2,function(q) {
      names(q) &lt;- rownames(data)
      samplepool &lt;- character()
      for (i in names(q)) {
        samplepool &lt;- append(samplepool,rep(i,times=q[i]))  
      }
      sampled &lt;- sample(samplepool,size=samplerate*length(samplepool),replace = F)
      tab &lt;- table(sampled)
      mat &lt;- match(names(tab),names(q))
      toret=numeric(length &lt;- length(q))
      names(toret) &lt;- names(q)
      toret[mat] &lt;- tab
      return(toret)
    })
  return(data.test)
  }
  </code></pre>
  
  <p>I need to be downsampling matrices with millions of entries.  I find this is quite slow (here I'm using a 1000x1000 matrix, which is about 20-100x smaller than my typical data size):</p>
  
  <pre><code>mat &lt;- matrix(sample(0:40,1000*1000,replace=T),ncol=1000,nrow=1000)
  colnames(mat) &lt;- paste0("C",1:1000)
  rownames(mat) &lt;- paste0("R",1:1000)
  system.time(matd &lt;- downsampled(mat,0.8))
  
  ##  user  system elapsed 
  ## 69.322  21.791  92.512 
  </code></pre>
  
  <p>Is there a faster/easier way to perform this operation that I haven't thought of?  </p>