Skip to content

Instantly share code, notes, and snippets.

@bayesball
Last active March 23, 2017 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayesball/2a78aaf69a0e54fe1a35fbedeb662e62 to your computer and use it in GitHub Desktop.
Save bayesball/2a78aaf69a0e54fe1a35fbedeb662e62 to your computer and use it in GitHub Desktop.
Functions for model/data simulations to learn about a binomial proportion
model_data_simulation <- function(P_vector,
mystat=sum,
N=100,
N_sim=10000){
require(ggplot2)
TH <- theme(
plot.title = element_text(
colour = "red",
size = 14,
hjust = 0.5,
vjust = 0.8,
angle = 0
)
)
name_mystat <- deparse(substitute(mystat))
one_sim <- function(mystat){
P <- sample(P_vector, size=1)
S <- mystat(rbinom(N, size=1, prob=P))
c(P, S)
}
S <- data.frame(t(replicate(N_sim, one_sim(mystat))))
names(S) <- c("P", "Statistic")
p <- ggplot(S, aes(P, Statistic)) +
geom_jitter(size=0.2) +
geom_smooth() +
ggtitle(paste("Model/Data Simulation \n Statistic:",
name_mystat, ", N =", N)) + TH
print(p)
S
}
inference_plot <- function(S, value_statistic){
require(ggplot2)
require(dplyr)
TH <- theme(
plot.title = element_text(
colour = "red",
size = 14,
hjust = 0.5,
vjust = 0.8,
angle = 0
)
)
S_new <- filter(S, Statistic==value_statistic)
limits <- quantile(S_new$P, c(0.25, 0.75))
p <- ggplot(S_new, aes(P)) +
geom_density(adjust=2) +
ggtitle(paste("Posterior of P when Statistic =",
value_statistic,
"\n 50% Interval Estimate")) + TH +
geom_vline(xintercept = limits, color="blue")
print(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment