R JAGS: Dimension mismatch - r
I am trying to run a model in JAGS but I got the following error:
Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, :
RUNTIME ERROR:
Cannot insert node into m[1]. Dimension mismatch
The model I specified is
model = "model
{
for (i in 1:N) {
z[i] ~ dnorm(m[i],tau)
m[i] <- beta0 + beta1*x + beta2*y
}
beta0 ~ dnorm(0.0,1.0E-3)
beta1 ~ dnorm(0.0,1.0E-3)
beta2 ~ dnorm(0.0,1.0E-3)
tau ~ dgamma(0.01,0.01)
}"
Then I specify the data and the initial values. Finally, I run the model.
data = list(z = wolfcamp$data, x = wolfcamp$coords[,1], y = wolfcamp$coords[,2], N = length(wolfcamp$data))
parameters=c("beta0","beta1","beta2","tau")
init1 = list(beta0 = 0, beta1 = 0, beta2 = 0, tau = 0)
init2 = list(beta0 = 1, beta1 = 1, beta2 = 1, tau = 1)
initial.values=list(init1, init2)
model1=jags(data=data, inits=initial.values,
parameters.to.save=parameters,
model.file=textConnection(model),
n.chains=2,
n.burnin=1000,
n.iter=11000)
Can you help me? Do you know why I get this error?
Thanks in advance.
It looks like you are not indexing through the vectors x and y, which causes a dimension mismatch.
Change this line:
m[i] <- beta0 + beta1*x + beta2*y
to this:
m[i] <- beta0 + beta1*x[i] + beta2*y[i]
and you should be good to go (so long as x and y are of length N)
Related
Compilation Error in jags.model: Runtime Error: Index out of range while running linear mixed model
I am trying to run linear mixed model in JAGS in R. I am trying to see influence of year as a random factor on speciesTotal. My code is: data_glmm<-read.csv("data_bbs_11_19.csv") Nyear<-length(levels(as.factor(data_glmm$Year))) Nyear<-9 jagsData_glmm<-with(data_glmm, list(SpeciesTotal=SpeciesTotal, StopTotal=StopTotal, Stratum=Stratum, Year=Year, N=length(SpeciesTotal), Nyear=Nyear)) lm1_jags <- function() { for (i in 1:N){ SpeciesTotal[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance) mu[i] <- alpha + a[Year[i]] + beta * StopTotal[i] # Random intercept for year } # Priors: alpha ~ dnorm(0, 0.01) # intercept sigma_a ~ dunif(0, 100) # standard deviation of random effect (variance between year) tau_a <- 1 / (sigma_a * sigma_a) # convert to precision for (j in 1:9){ a[j] ~ dnorm(0, tau_a) # random intercept for each year } beta ~ dnorm(0, 0.01) # slope sigma ~ dunif(0, 100) # standard deviation of fixed effect (variance within year) tau <- 1 / (sigma * sigma) # convert to precision } init_values <- function(){ list(alpha = rnorm(1), sigma_a = runif(1), beta = rnorm(1), sigma = runif(1)) } params <- c("alpha", "beta", "sigma", "sigma_a") fit_lm3 <- jags(data = jagsData_glmm, inits = init_values, parameters.to.save = params, model.file = lm1_jags, n.chains = 3, n.iter = 20000, n.burnin = 5000, n.thin = 10, DIC = F) While running this code, I am getting following error: Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, : RUNTIME ERROR: Compilation error on line 5. Index out of range taking subset of a Any suggestion would be really appreciated.
Problem adjusting a linear model with JAGS
I am trying to adjust a linear model with JAGS but I'm having trouble with the code. I'm writing: library(R2jags) library(BEST) base<-data.table::data.table(read.csv("/Users/franco/Documents/Todo/UNAM/Facultad\ de\ Ciencias/Asignaturas\ Actuaría/Análisis\ Bayesiano\ de\ Datos/Tareas/Tarea-Examen\ 2/FootballLeague.csv")) X <- cbind(1,as.matrix(base[,-c(1,2,12)])) y <-as.matrix(base[,2]) n <- length(y) m <- ncol(X) model.jags <- function(){ tau ~ dgamma(0.01, 0.01) for(i in 1:m){ beta[i] ~ dnorm(0,0.001) } for (i in 1:n){ y[i] ~ dnorm(x[i,]%*%beta,tau) } sigma <- pow(tau,-1) } jags.params <- c("beta","sigma") jags.modelo <- jags(model.file=model.jags,parameters.to.save=jags.params, data = list('n' = n, 'y' = y, 'x' = X, 'm'=m), n.chains = 2, n.thin=1, DIC=FALSE, n.burnin = 10000, n.iter = 20000) And R throws this error: Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, : RUNTIME ERROR: Compilation error on line 8. Dimension mismatch in subset expression of y. I don't know which is the error :/ Can someone help me, please.
Rstan Error: Cannot coerce type 'closure' to vector of type 'character'
I'm following the blog post here (https://mattocci27.github.io/assets/poilog_mix/poilog_mix.html) exactly, but keep running into a strange error. To be totally precise, I am running: library(rstan) mu <- c(log(50), log(400)) sigma <- c(0.8, 0.2) theta <- 0.8 N <- 100 z <- rbinom(N, 1, 1 - theta) + 1 log_lambda <- rnorm(N, mu[z], sigma[z]) Y <- rpois(N, exp(log_lambda)) rstan_options(auto_write = TRUE) options(mc.cores = parallel::detectCores()) list_dat <- list(N = N, y = Y) fit_cp <- stan(file = "poilog_mix_cp.stan", data = list_dat, iter = 2000, warmup = 1000, thin = 1, chains = 4, refresh = 500, control = list(adapt_delta = 0.9, max_treedepth = 20)) with the file "poilog_mix_cp.stan" as follows: data{ int<lower=0> N; int y[N]; } parameters { ordered[2] mu; real<lower=0> sigma[2]; real<lower=0, upper=1> theta; vector[N] log_lambda[2]; } model { sigma ~ cauchy(0, 2.5); mu ~ normal(0, 10); theta ~ beta(2, 2); for (i in 1:2) log_lambda[i,] ~ normal(mu[i], sigma[i]); for (n in 1:N) target += log_mix(theta, poisson_log_lpmf(y[n] | log_lambda[1, n]), poisson_log_lpmf(y[n] | log_lambda[2, n])); } but at the step of fitting the model, I get the following error: Error in as.character(sys.call(sys.parent())[[1L]]) : cannot coerce type 'closure' to vector of type 'character' I'm not sure what's going on, since I'm just copying the blog post.
Bayesian Beta regression Model -- Error in jags: Invalid parent value
I'm trying to run a Bayesian pooled model in jags through R and getting an error message I found from people who have encountered similar problems that it could be triggered by values of the priors, negative value, log of negative, syntax errors etc. I have eliminated all of these but the error persists. ## just for the prediction pred.jac <- seq(min(test.bayes$Latitude), max(test.bayes$Latitude), 10) data = list( jac = test.bayes$Jaccard, lat = test.bayes$Latitude, pred.jac = pred.jac) inits = list( list(alpha = 1, beta = 2.5, sigma = 50), list(alpha = 2, beta = 1.5, sigma = 20), list(alpha = 3, beta = 0.75, sigma = 10)) { sink("BetaPooledJAGS.R") cat(" model{ # priors alpha ~ dnorm(0, 0.0001) beta ~ dnorm(0, 0.0001) sigma ~ dunif(0, 10) # likelihood for (i in 1:length(jac)) { mu[i] <- alpha + beta * lat[i] a[i] <- ((1 - mu[i]) / (sigma^2) - 1 / mu[i]) * mu[i]^2 b[i] <- alpha * (1 / mu[i] - 1) jac[i] ~ dbeta(a[i], b[i]) } # predicted jaccard as derived quantities for (i in 1:length(pred.jac)) { mu_pred[i] <- alpha + beta * lat[i] mu_pred1[i] <- exp(mu_pred[i]) } } ",fill = TRUE) sink() } n.adapt = 3000 n.update = 5000 n.iter = 5000 jm.pooled = jags.model(file="BetaPooledJAGS.R", data = data, n.adapt = n.adapt, inits = inits, n.chains = length(inits)) When I run the code, I get the error below: Error in jags.model(file = "BetaPooledJAGS.R", data = data, n.adapt = n.adapt, : Error in node jac[1] Invalid parent values Here's the link to a subset of my data. https://fil.email/IuwgYhKs
You're getting negative values for b with those initials if lat is positive, and b must be > 0 in a beta distribution, in JAGS, and more generally. E.g. using initials from inits[[1]]: mu = 1 + 2.5*lat assuming lat is positive, then mu > 1 b = 1 * (1/mu-1) And 1/mu < 1 if mu>1, so 1/mu - 1 < 0. Therefore b = 1*-ve so b<0
Censoring in rjags - Invalid parent values
I'm having troubles reimplementing a model from winbugs on rjags. I'm getting the Invalid parent values error which is the error you get when censoring was not correctly setup, but I can't see my mistake. This is the original model on WinBugs: model { for(i in 1 : N) { times[i] ~ dweib(v, lambda[i]) T(censor[i],) lambda[i] <- exp(beta0 + beta1*type[i]) S[i] <- exp(-lambda[i]*pow(times[i],v)); f[i] <- lambda[i]*v*pow(times[i],v-1)*S[i] h[i] <- f[i]/S[i] } beta0 ~ dnorm(0.0, 0.0001) beta1 ~ dnorm(0.0, 0.0001) v ~ dexp(0.001) median0 <- pow(log(2) * exp(-beta0), 1/v) median1 <- pow(log(2) * exp(-beta0-beta1), 1/v) } Setting up a reproducible example: type <- as.factor(c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)) censor <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,882,892,1031, 1033,1306,1335,0,1452,1472,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,381,0,0,0,0,0,0,0,0,0,529,0, 0,0,0,0,0,0,0,0,945,0,0,1180,0,0,1277,1397,1512,1519) times <-c (17,42,44,48,60,72,74,95,103,108,122,144,167,170,183,185,193,195,197,208,234,235,254,307,315,401, 445,464,484,528,542,567,577,580,795,855,NA,NA,NA,NA,NA,NA,1366,NA,NA,1,63,105,129,182,216,250,262, 301,301,342,354,356,358,380,NA,383,383,388,394,408,460,489,499,524,NA,535,562,675,676,748,748,778, 786,797,NA,955,968,NA,1245,1271,NA,NA,NA,NA) df <- tibble(type = type, censor = censor, time = times) %>% mutate(censor_limit = replace(censor, censor == 0, max(times, na.rm = TRUE))) %>% mutate(is_censored = ifelse(is.na(time), 1, 0)) %>% mutate(time_init = ifelse(is_censored == 1, censor_limit + 1, NA)) df$censor <- NULL head(df) And this is the rjags part: m <- textConnection("model { for(i in 1 : N) { isCensored[i] ~ dinterval(times[i], censorLimit[i]) times[i] ~ dweib(v, lambda[i]) lambda[i] <- exp(beta0 + beta1*type[i]) S[i] <- exp(-lambda[i]*pow(times[i],v)); f[i] <- lambda[i]*v*pow(times[i],v-1)*S[i] h[i] <- f[i]/S[i] } beta0 ~ dnorm(0.0, 0.0001) beta1 ~ dnorm(0.0, 0.0001) v ~ dexp(0.001) # Median survival time median0 <- pow(log(2) * exp(-beta0), 1/v) median1 <- pow(log(2) * exp(-beta0-beta1), 1/v) }") d <- list(N = nrow(df), times = df$time, type = df$type, isCensored = df$is_censored, censorLimit = df$censor_limit) inits1 = function() { inits = list(v = 1, beta0 = 0, beta1=0, times = df$time_init) } mod <- jags.model(m, data = d, inits = inits1, n.chains = 3) update(mod, 1e3) mod_sim <- coda.samples(model = mod, variable.names = c("lambda", "median0", "median1"), n.iter = 5e3) mod_csim <- as.mcmc(do.call(rbind, mod_sim)) Output: Compiling model graph Resolving undeclared variables Allocating nodes Graph information: Observed stochastic nodes: 164 Unobserved stochastic nodes: 19 Total graph size: 910 Initializing model Deleting model Error in jags.model(m, data = d, inits = inits1, n.chains = 3): Error in node h[35] Invalid parent values