Skip to content

Instantly share code, notes, and snippets.

@jsta
Created May 1, 2017 00:13
Show Gist options
  • Save jsta/215b31f828d2d0fbdf994cf8de67ba21 to your computer and use it in GitHub Desktop.
Save jsta/215b31f828d2d0fbdf994cf8de67ba21 to your computer and use it in GitHub Desktop.
Fit a simple bayesian regression model using the iris dataset
library(rjags)
data(iris)
independent <- iris$Petal.Length
dependent <- matrix(iris$Petal.Width)
lm.m <- lm(independent~dependent)
dependent <- cbind(1, dependent)
n <- nrow(dependent)
p <- ncol(dependent)
data <- list("y" = independent, "X" = dependent, "n" = n, "p" = p)
inits <- list(beta = coefficients(lm.m), sigma.sq = 4000)
modelstring <- "
model{
for(i in 1:n){
y[i] ~ dnorm(mu[i], tau.sq)
}
mu <- X%*%beta
for(i in 1:p){
beta[i] ~ dnorm(0, 0.000001)
}
tau.sq <- 1/sigma.sq
sigma.sq ~ dgamma(4, 0.001)
sigma.sq.prior.check ~ dgamma(4, 0.001)
}
"
jags.m <- jags.model(file = textConnection(modelstring), data = data, inits = inits, n.chains = 3, n.adapt = 1000)
params <- c("beta", "sigma.sq", "sigma.sq.prior.check")
samps <- coda.samples(jags.m, params, n.iter = 40000)
plot(samps, density = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment