使用rstan拟合graded response model时数据声明语法报错求助
Let's break down the issues with your Stan code and fix them step by step:
1. Root Cause of the Syntax Error
The parser error is triggered by unnecessary spaces between type keywords (int, real) and their constraint brackets (<...>). Stan's strict grammar requires no whitespace between the type and the constraint modifier.
Looking at your original code, lines like these are invalid:
int <lower=0> n_student; int <lower=0> n_item;
The space between int and < violates Stan's syntax rules, which is exactly what the parser is flagging.
2. Additional Compatibility & Style Fixes
Beyond the critical syntax error, there are two more adjustments for modern Stan compatibility and best practices:
- Space between variable and array brackets: While not a syntax error,
alpha [n_item]should bealpha[n_item](no space) to align with standard Stan style conventions. - Deprecated log probability function:
ordered_logistic_logis outdated in recent Stan versions. Useordered_logistic_lpmf(log probability mass function) instead in the generated quantities block for consistent, supported syntax.
3. Corrected Stan Code
Here's the fully fixed version of your model:
data{ int<lower=2, upper=4> K; // number of categories int<lower=0> n_student; int<lower=0> n_item; int<lower=1,upper=K> Y[n_student,n_item]; } parameters { vector[n_student] theta; real<lower=0> alpha[n_item]; ordered[K-1] kappa[n_item]; // category difficulty real mu_kappa; // mean of the prior distribution of category difficulty real<lower=0> sigma_kappa; // sd of the prior distribution of category difficulty } model{ alpha ~ cauchy(0,5); theta ~ normal(0,1); for (i in 1:n_item){ for (k in 1:(K-1)){ kappa[i,k] ~ normal(mu_kappa,sigma_kappa); } } mu_kappa ~ normal(0,5); sigma_kappa ~ cauchy(0,5); for (i in 1:n_student){ for (j in 1:n_item){ Y[i,j] ~ ordered_logistic(theta[i]*alpha[j],kappa[j]); } } } generated quantities { vector[n_item] log_lik[n_student]; for (i in 1:n_student){ for (j in 1:n_item){ log_lik[i, j] = ordered_logistic_lpmf(Y[i, j] | theta[i]*alpha[j], kappa[j]); } } }
4. Verification
Run your existing R code with this corrected Stan file, and the syntax error should disappear entirely. The model will compile and begin sampling with your simulated response data as expected.
内容的提问来源于stack exchange,提问作者duckmayr

