Hey all. I have a somewhat related issue with these data. I’m fitting a simplified version of a model from the 2nd edition of Statistical Rethinking. In Section 12.4, McElreath introduced an ordered categorical predictor, education, which has 8 levels ranging from "Elementary School"
to "Graduate Degree"
. In McElreath’s style of notation, the full version of the model was
where R is the ordinal response variable, E is our new ordered categorical predictor, and A through C are other predictors. I’m dropping those other predictors here to streamline the model and the code, which simplifies my model for \phi_i to
I’m currently working through the rstan code, with this version running successfully:
library(tidyverse)
library(tidybayes)
library(rstan)
data(Trolley, package = "rethinking")
edu_levels_vec <- c("Elementary School", "Middle School", "Some High School", "High School Graduate",
"Some College", "Bachelor's Degree", "Master's Degree", "Graduate Degree")
stan_data <- Trolley |>
mutate(edu_new = factor(edu, levels = edu_levels_vec)) |>
select(response, edu_new) |>
compose_data(alpha = rep(2, times = 7))
model_code <- '
data {
int n;
array[n] int response;
array[n] int edu_new;
vector[7] alpha; // For the `delta` prior
}
parameters {
ordered[6] kappa;
real bE;
simplex[7] delta;
}
model {
vector[n] phi;
vector[8] delta_j;
delta_j = append_row(0, delta);
for (i in 1:n) phi[i] = bE * sum(delta_j[1:edu_new[i]]);
response ~ ordered_logistic(phi, kappa);
kappa ~ normal(0, 1.5);
bE ~ normal(0, 1);
delta ~ dirichlet(alpha);
}
'
fit1 <- stan(
model_code = model_code,
data = stan_data,
cores = 3, chains = 3, seed = 12)
Now we get to the heart of my problem. I’m trying to vectorize the code for the phi
, and can’t seem to get it right. Here’s my current attempt:
'
model {
vector[n] phi;
vector[8] delta_j;
delta_j = append_row(0, delta);
phi = bE * sum(delta_j[1:edu_new]); // Only this line has chaged.
response ~ ordered_logistic(phi, kappa);
kappa ~ normal(0, 1.5);
bE ~ normal(0, 1);
delta ~ dirichlet(alpha);
}
'
When I try running the model this way, I get this error message:
Error in stanc(file = file, model_code = model_code, model_name = model_name, :
0
Semantic error in 'string', line 17, column 27 to column 34:
-------------------------------------------------
15: delta_j = append_row(0, delta);
16:
17: phi = bE * sum(delta_j[1:edu_new]); // Only this line has chaged.
^
18: response ~ ordered_logistic(phi, kappa);
19:
-------------------------------------------------
Range bound must be of type int. Instead found type array[] int.
I don’t understand what this is prompting me to do. Is there a way to vectorize phi
?