Skip to content

Instantly share code, notes, and snippets.

@robbymeals
Created October 31, 2012 15:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robbymeals/3987839 to your computer and use it in GitHub Desktop.
Save robbymeals/3987839 to your computer and use it in GitHub Desktop.
Binomial Proportion Post Gists 2
### Function: Likelihood Plot Values
likelihood <- function(N,Y){
a <- Y + 1
b <- N - Y + 1
dom <- seq(0,1,0.005)
val <- dbeta(dom,a,b)
return(data.frame('x'=dom, 'y'=val))
}
### Function: Mean of Posterior Beta
mean_of_posterior <- function(m,n,N,Y){
a <- Y + (n*m) -1
b <- N - Y + (n*(1-m)) - 1
E_posterior <- a / (a + b)
return(E_posterior)
}
### Function: Mode of Posterior Beta
mode_of_posterior <- function(m,n,N,Y){
a <- Y + (n*m) -1
b <- N - Y + (n*(1-m)) - 1
mode_posterior <- (a-1)/(a+b-2)
return(mode_posterior)
}
### Function: Posterior Plot Values
posterior <- function(m,n,N,Y){
a <- Y + (n*m) -1
b <- N - Y + (n*(1-m)) - 1
dom <- seq(0,1,0.005)
val <- dbeta(dom,a,b)
return(data.frame('x'=dom, 'y'=val))
}
### Function: Prior Plot Values
prior <- function(m,n){
a = n * m
b = n * (1 - m)
dom <- seq(0,1,0.005)
val <- dbeta(dom,a,b)
return(data.frame('x'=dom, 'y'=val))
}
### Function: Std Dev of Posterior Beta
sd_of_posterior <- function(m,n,N,Y){
a <- Y + (n*m) -1
b <- N - Y + (n*(1-m)) - 1
sigma_posterior <- sqrt((a*b)/(((a+b)^2)*(a+b+1)))
return(sigma_posterior)
}
@ellios84
Copy link

ellios84 commented Jun 2, 2016

Dear robbymeals,

I am using your explanation and code to estimate the posterior beta distribution of a beta-binomial model. First of all, thanks a lot for sharing your post (http://www.r-bloggers.com/to-the-basics-bayesian-inference-on-a-binomial-proportion/), which I found very clear and useful.
Anyway, I would have some concerns about the function calculating the posterior distribution. In particular:

posterior <- function(m,n,N,Y){
a <- Y + (n_m) -1
b <- N - Y + (n_(1-m)) - 1
[...]
}

Why do you add a "-1" term in the calculus of posterior alpha and beta parameters? The relationship between alpha_prior with alpha_posterior, and beta_prior with beta_posterior turns out to be alpha_posterior = Y + alpha_prior and beta_posterior = N - Y + beta_prior, respectively.

Which is the meaning of this "-1"? Maybe am I missing something?

Thanks a lot for any explanation,
kind regards,
Elia

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment