Reputation: 151
I try to build a varying-intercept model in RStan, attempting to predict female contraceptive use in one region of India based on age, number of children, and whether or not they live in an urban area, with intercepts varying by district.
Below is my code:
stan_list <- list(N = nrow(train), contra = (train$contraceptive_use),
district = train$district,
urban = train$urban,
children = train$living.children,
age = train$age_mean)
str(stan_list)
code <- '
data {
int<lower=0> N; // number of observations
int<lower=1, upper=60> district[N]; // number of districts (J = 60)
vector[N] contra; // dependent variable
vector[N] urban; // independent variable 1
vector[N] children; // independent variable 2
vector[N] age; // independent variable 3
}
parameters {
vector[60] beta_0; // intercept estimated with 60 districts
real mu_beta_0; // mean for intercepts
real sigma_beta_0; // standard error for the intercept
real beta_1;
real beta_2;
real beta_3;
}
transformed parameters {
vector[N] contra_hat; // create one variable with predictions for each observation
for (i in 1:N) { // loop for all cases
contra_hat[i] <- beta_0[district[i]] + beta_1 * urban[i] + beta_2 * children[i] + beta_3 * age[i];
}
}
model {
mu_beta_0 ~ normal(0, 100);
sigma_beta_0 ~ exponential(0.1);
beta_0 ~ normal(mu_beta_0, sigma_beta_0);
beta_1 ~ normal(4, sigma_beta_0);
beta_2 ~ normal(-3, sigma_beta_0);
beta_3 ~ normal(-2, sigma_beta_0);
// Likelihood
contra ~ bernoulli_logit(contra_hat);
}
'
# Translate the model into C++
model1 <- stan(model_code = code, data = stan_list, iter = 2000, chains = 4)
When I define the model above, I get the following error message:
Warning (non-fatal): assignment operator <- deprecated in the Stan language; use = instead.
No matches for:
vector ~ bernoulli_logit(vector)
Available argument signatures for bernoulli_logit:
int ~ bernoulli_logit(real)
int ~ bernoulli_logit(real[])
int ~ bernoulli_logit(vector)
int ~ bernoulli_logit(row vector)
int[] ~ bernoulli_logit(real)
int[] ~ bernoulli_logit(real[])
int[] ~ bernoulli_logit(vector)
int[] ~ bernoulli_logit(row vector)
require real scalar return type for probability function.
error in 'model323f123010a7_b7f3052df681e80851694dd14c79969c' at line 36, column 38
-------------------------------------------------
34:
35: // Likelihood
36: contra ~ bernoulli_logit(contra_hat);
^
37: }
-------------------------------------------------
Error in stanc(file = file, model_code = model_code, model_name = model_name, :
failed to parse Stan model 'b7f3052df681e80851694dd14c79969c' due to the above error.
Can anyone help, please?
Upvotes: 2
Views: 925
Reputation: 4990
The outcome has to be declared in the data block as an integer array in order to be used by bernoulli_logit
, as in
int<lower=0,upper=1> contra[N];
Upvotes: 2