开始使用免费开始使用

Simulating the dependence of X on p

In your quest for election to public office, your campaign polls 10 likely voters. Let \(X\) be the number that support you. Of course, \(X\) varies from sample to sample and depends upon \(p\), your underlying support in the broader population. Since \(X\) is a count of successes in 10 independent trials, each having probability of success \(p\), you can model its dependence on \(p\) by the Binomial distribution: Bin(10, \(p\)).

You will simulate the Binomial model using random samples from the rbinom(n, size, prob) function. This vectorized function draws n samples from a Bin(size, prob) distribution. Given a vector of prob values, the first prob value will be used for the first draw, the second prob value will be used for the second draw, etc.

本练习是课程的一部分

Bayesian Modeling with RJAGS

查看课程

练习说明

  • Define a seq() of 1000 possible values of \(p\) that range from 0 to 1. Store this as p_grid.
  • Use rbinom() to simulate one poll result \(X\) for each of the 1000 \(p\) in p_grid. Assign these to poll_result.
  • The likelihood_sim data frame combines p_grid and poll_result. Use ggplot() with a geom_density_ridges() layer to illustrate the distribution of p_grid values (x axis) from which each poll_result was simulated (y axis).

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Define a vector of 1000 p values    
p_grid <- seq(from = ___, to = ___, length.out = ___)

# Simulate 1 poll result for each p in p_grid   


# Create likelihood_sim data frame
likelihood_sim <- data.frame(p_grid, poll_result)    

# Density plots of p_grid grouped by poll_result
ggplot(likelihood_sim, aes(x = ___, y = ___, group = poll_result)) + 
    geom_density_ridges()
编辑并运行代码