title: downsampling a matrix in R
body: <p>I have a matrix Q that is relatively high dimensional (100X500000), and I want to downsample it. By downsample, I will explain with an example.</p>
  
  <p>Let Q =</p>
  
  <pre><code>1 4 9
  3 2 1
  </code></pre>
  
  <p>and downsample size= n. I want to draw n balls from a jar of sum(Q) = 20 balls, each ball colored 1 of 6 ways corresponding to a different index pair of the matrix. It's like I have 1 ball of color A, 4 balls of color B, etc, and I'm drawing n balls without replacement.</p>
  
  <p>I want it to be returned in the same format, as a matrix.  One example return value, for example, downsample(Q, 3) =</p>
  
  <pre><code>0 0 2
  1 0 0
  </code></pre>
  
  <p>My approach is trying to use sample:</p>
  
  <pre><code>sample(length(as.vector(Q)), size=n, replace=FALSE, prob = as.vector(Q))
  </code></pre>
  
  <p>However the problem with this is, sample considers 1:length(as.vector(Q)) as all the balls I have, so I can't draw more than length(as.vector(Q)) balls since I'm not replacing my balls.</p>
  
  <p>So then to adapt my method, I would need to update my prob by subtracting 1 from this vector, and call sample one by one using a for loop of some sort.  It doesn't sound like nice code.</p>
  
  <p>Is there a better way to do this in a R-friendly, no for loop way?</p>