Hi, I am trying to run a multinomial model with several predictors. The code below works if I have one predictor but throws an error when I add another one. I have two questions please. Given the error message is the issue in the model failing to evaluate the probability at some initial value, is it an index out of range or both?
If it’s an index out range, why does it happen when I add a second predictor that’s very similar to the first predictor? The data and the code are below as well as the error message. Thank you.
A<-rbinom(1000,1,.35)
for (i in 1:length(A)){
Y[i]=ifelse( A[i]==1, sample(1:4, 1, replace=TRUE, prob=c(0.75, 0.10, .10, 0.05)),
sample(1:4, 1, replace=TRUE, prob=c(0.25, 0.25, .25, 0.25)))
}
for (i in 1:length(A)){
B[i]=ifelse( A[i]==1, 0,
sample(0:1, 1, replace=TRUE, prob=c(.45, .55)))}
Y<-as.numeric(Y)
K=4
N=1000
D=1
stan_data2 <- list(Y=Y, A=A, K=K, D=D, N=N, B=B)
stan_program2<-"
data {
int K;
int N;
int D;
int Y[N];
int A[N]; // dummy predictor
int B[N];
//real time[N]; // adding a continuous predictor
}
parameters {
real a[K-1]; // intercepts for each subject area minus the reference
real bA[K-1]; // beta for the predictor
real bB[K-1];
//matrix[D, K] alpha_A; // we have a matrix because there is a beta for A for each Y category. So in this case is 1:4 matrix.
}
model {
a ~ normal(0,1); //prior for alpha
bA ~ normal(0,1); //prior for betas
bB ~ normal(0,1);
// likelihood with predictor
for ( i in 1:N ) {
vector[K] p;
for ( k in 1:(K-1) )
p[k] = a[k] + bA[k] * A[i]+bB[K] * B[i];
p[K] = 0; // this sets the last category as a fixed reference for other categories
Y[i] ~ categorical_logit( p );
}
}
"
fit2<-stan(model_code = stan_program2, data = stan_data2,
warmup = 1000, iter = 5000, chains = 2, cores = 4,seed = 12)
Chain 1 Unrecoverable error evaluating the log probability at the initial value.
Chain 1 Exception: array[uni, ...] index: accessing element out of range. index 4 out of range; expecting index to be between 1 and 3 (in 'C:/Users/BOGDAN~1/AppData/Local/Temp/Rtmp2BA4CD/model-27c826e45a93.stan', line 26, column 12 to column 52)