Get startedGet started for free

A conditional shortcut

Great, you've now done some Bayesian computation, without doing any simulation! The plot you produced should be similar to the posterior distribution you calculated in chapter 3. However, you can see that it required an awful lot of code, isn't there anything we can cut?

Yes, there is! You can directly condition on the data, no need to first create the joint distribution.

This exercise is part of the course

Fundamentals of Bayesian Data Analysis in R

View Course

Exercise instructions

  • Set n_visitors directly to 6, just replace the seq-statement.
  • Now you can remove the line that conditions on the data, and the line after that, that normalizes pars$probability.
  • Take an extra look at the final code and convince yourself that the result of this modified code will be the same as before. :)

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Simplify the code below by directly conditioning on the data
n_ads_shown <- 100
proportion_clicks <- seq(0, 1, by = 0.01)
n_visitors <- seq(0, 100, by = 1)
pars <- expand.grid(proportion_clicks = proportion_clicks,
                    n_visitors = n_visitors)
pars$prior <- dunif(pars$proportion_clicks, min = 0, max = 0.2)
pars$likelihood <- dbinom(pars$n_visitors, 
    size = n_ads_shown, prob = pars$proportion_clicks)
pars$probability <- pars$likelihood * pars$prior
pars$probability <- pars$probability / sum(pars$probability)
pars <- pars[pars$n_visitors == 6, ]
pars$probability <- pars$probability / sum(pars$probability)
plot(pars$proportion_clicks, pars$probability, type = "h")
Edit and Run Code