6 thoughts on “A simple explanation of rejection sampling in R

  1. Pingback: Distilled News | Data Analytics & R

  2. Nice post; thanks.

    A small observation on the R code which will improve the efficiency. These steps could be simplified:

    sampled <- data.frame(proposal = runif(100000,0,1))
    sampled$targetDensity <- dbeta(sampled$proposal, 3,6)
    maxDens = max(sampled$targetDensity, na.rm = T)
    sampled$accepted = ifelse(runif(100000,0,1) < sampled$targetDensity / maxDens, TRUE, FALSE)
    

    to

    sampled <- data.frame(proposal = runif(100000, 0, 1))
    sampled <- transform(sampled, targetDensity = dbeta(proposal, 3, 6))
    sampled <- transform(sampled, accepted = runif(100000, 0, 1) < targetDensity / 
                             max(targetDensity, na.rm = TRUE))
    

    The main change (the other changes just suit my style and abhorrence of $ in code 🙂 is to ditch the ifelse() and compute the logical vector accepted directly from the comparison operator <; the ifelse() bit is making this run ~ an order magnitude slower (on my machine) than just computing the comparison directly (in fact your code does this, but adds the ifelse() bit on top).

    I’m looking forward to the sequential MC post now.

    Like

  3. Pingback: A simple explanation of rejection sampling in R — theoretical ecology – Encaion

  4. Pingback: Bayes’ Theorem Primer – Connections

Leave a comment