title: r - Sampling from a grid of probabilities (Bayesian posterior approximation)
body: <p>I am doing a Bayesian analysis, and I am trying to estimate two parameters. To approximate the posterior distribution, I have constructed a fine grid and computed the posterior probability for each element in the grid. I normalized it so that the grid sums to 1.</p>
  
  <p>Now I am interested in sampling from the distribution. This is what I have so far:</p>
  
  <pre><code>sampleGrid &lt;- function(post.grid, mu.grid, sig2.grid) {
    value &lt;- sample(post.grid, 1, prob=post.grid)
    index &lt;- which(post.grid == value) 
    col &lt;- as.integer(index/nrow(post.grid))+1
    row &lt;- index-(col-1)*nrow(post.grid)
    return(c(mu.grid[row], sig2.grid[col]))
  }
  </code></pre>
  
  <p>However, I run into problems with runtime when I want to sample a lot because I use a for loop: </p>
  
  <pre><code>for(i in 1:nrow(sample.grid)) {
    sample.grid[i, ] &lt;- sampleFromGrid(post.grid, mu.grid, sig2.grid)
  }
  </code></pre>
  
  <p>I was wondering if there was a way to vectorize this. My attempt was:</p>
  
  <pre><code>vectorizedSampleFromGrid &lt;- function(post.grid, mu.grid, sig2.grid, n){
      values &lt;- sample(post.grid, n, replace=T, prob=post.grid)
      index &lt;- which(post.grid %in% values)
      if(length(values)!=length(index)) {
          temp.df &lt;- count(values)
          index &lt;- which(post.grid %in% temp.df[,1])
          temp.df &lt;- cbind(temp.df, index)
          temp.df &lt;- temp.df[temp.df[, 2] &gt; 1, ]
          for(i in 1:nrow(temp.df)) {
              index &lt;- c(index, rep(temp.df[i, 3], temp.df[i,2]-1))
          }
      }
      col &lt;- as.integer(index/nrow(post.grid))+1
      row &lt;- index-(col-1)*nrow(post.grid)
      return(cbind(mu.grid[row], sig2.grid[col]))
  }
  </code></pre>
  
  <p>I know that some elements will be sampled more than once. What I am trying to do is append those indexes multiple times to the original index list based on how many times they were sampled. However when I do this the result is not correct.</p>
  
  <p>If anyone can offer any advice, I would greatly appreciate it. </p>