Compiling error help (beginner)

Capture - Copy

I’m currently in the process of modelling the above and I’ve confused myself a little. Below is my code, hopefully, someone with a little bit more experience can help with this. I’ve manually rearranged the log component as the logit function was adding to my confusion.


write("
data {
// Define variables in data
// Number of observations (an integer)
int<lower=0> N;
// Variables
int tooth30[N];
int<lower=0> age[N];
int<lower=0> smoked[N];
}
parameters {
real < lower = 0 > beta_0;
real < lower = 0 > beta_1;
real < lower = 0 > beta_2;
}
model {
vector[N] p;
beta_0 ~ normal(0,100);
beta_1 ~ normal(0,100);
beta_2 ~ normal(0,100);
for(i in 1:N){
p[i] = exp(beta_0 + beta_1age + beta_2smoked)/(1+beta_0 + beta_1age + beta_2smoked);
//
tooth30[i] ~ binomial(1,p[i])
}
}
",
file = “test_stan_code.stan”
)


Expression is ill formed.
error in ‘model3dd83880558b_exam_stan_code’ at line 22, column 56

20:         beta_2 ~ normal(0,100);
21:         for(i in 1:N){        
22:           p[i] = exp(beta_0 + beta_1*age + beta_2*smoked)/(1+beta_0 + beta_1*age + beta_2*smoked);
                                                           ^
23:         //

Error in stanc(“exam_stan_code.stan”) :
failed to parse Stan model ‘exam_stan_code’ due to the above error

This is the error I’m getting, I’m aware that the form of smoked and possibly age are incorrect. Smoked is a 1 or 0 value, age is an integer.

Your age and smoked are arrays so you should index into them

for(i in 1:N){
  p[i] = exp(beta_0 + beta_1*age[i] + beta_2*smoked[i])/(1 + beta_0 + beta_1*age[i] + beta_2*smoked[i]);
  tooth30[i] ~ binomial(1,p[i]);
}

Also, that denominator is missing an exp(...). Stan has binomial_logit distribution that handles the transformation automatically so the above could be written as

for(i in 1:N){
  real logit_p = beta_0 + beta_1*age[i] + beta_2*smoked[i];
  tooth30[i] ~ binomial_logit(1, logit_p);
}

which, in my opinion, is clearer.