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)


    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.


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

  4. Pingback: Bayes’ Theorem Primer – Connections

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s