Skip to content

Instantly share code, notes, and snippets.

@rasmusab
Created April 6, 2014 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rasmusab/10011579 to your computer and use it in GitHub Desktop.
Save rasmusab/10011579 to your computer and use it in GitHub Desktop.
Correlation in rJAGS
library(rjags)
library(mvtnorm) # to generate correlated data with rmvnorm.
library(car) # To plot the estimated bivariate normal distribution.
set.seed(31415)
mu <- c(10, 30)
sigma <- c(20, 40)
rho <- -0.7
cov_mat <- rbind(c( sigma[1]^2 , sigma[1]*sigma[2]*rho ),
c( sigma[1]*sigma[2]*rho, sigma[2]^2 ))
x <- rmvnorm(30, mu, cov_mat)
plot(x, xlim=c(-125, 125), ylim=c(-100, 150))
model_string <- "
model {
for(i in 1:n) {
x[i,1:2] ~ dmnorm(mu[], prec[ , ])
}
# Constructing the covariance matrix and the corresponding precision matrix.
prec[1:2,1:2] <- inverse(cov[,])
cov[1,1] <- sigma[1] * sigma[1]
cov[1,2] <- sigma[1] * sigma[2] * rho
cov[2,1] <- sigma[1] * sigma[2] * rho
cov[2,2] <- sigma[2] * sigma[2]
# Flat priors on all parameters which could, of course, be made more informative.
sigma[1] ~ dunif(0, 1000)
sigma[2] ~ dunif(0, 1000)
rho ~ dunif(-1, 1)
mu[1] ~ dnorm(0, 0.001)
mu[2] ~ dnorm(0, 0.001)
# Generate random draws from the estimated bivariate normal distribution
x_rand ~ dmnorm(mu[], prec[ , ])
}
"
data_list = list(x = x, n = nrow(x))
# Use classical estimates of the parameters as initial values
inits_list = list(mu = c(mean(x[, 1]), mean(x[, 2])),
rho = cor(x[, 1], x[, 2]),
sigma = c(sd(x[, 1]), sd(x[, 1])))
jags_model <- jags.model(textConnection(model_string), data = data_list, inits = inits_list,
n.adapt = 500, n.chains = 3, quiet = T)
update(jags_model, 500)
mcmc_samples <- coda.samples(jags_model, c("mu", "rho", "sigma", "x_rand"),
n.iter = 5000)
@gonzalezivan90
Copy link

Nice!!

@mbedward
Copy link

Thanks! Just what I was looking for.

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