I am looking for some debugging help on the function code below. A little context. I have run a mixed logit model using the mlogit package in R, and have generated a panel model without correlations between the random coefficients.
In total, I have 11 coefficients that I am looking to use to generate a predictive model by running a simulation. I am aiming to achieve this by running a function, noted below (a variation on the code in the book Simulations in R for Marketing Research and Analytics:
predict.mnl <- function(model, data, nresp=2000)
{
library(MASS)
data.model <- model.matrix(update(model$formula, 0 ~ .), data = data)
coef.mu <- model$coef[1:11] **#Coefficients**
coef.sd <- abs(model$coef[12:22]) #**SD to end, corrected for abs value**
for (j in 1:11) {
draws[j,] <- rnorm(n=nresp, coef.mu[j], coef.sd[j])
shares <- matrix(NA, nrow=nresp, ncol=nrow(data))
}
for (i in 1:nresp) {
utility <- data.model%*%draws[i, ]
share = exp(utility)/sum(exp(utility))
shares[i, ] <- share
}
cbind(colMeans(shares), data)
}
predict.mnl(m3, new.data)
Effectively what I am trying to do is take the coefficients and standard deviations, generate individual level estimates of each of the coefficients for 2000 'participants' in a new matrix by drawing random samples (in the for (j in 1:11) loop), create the predicted share for each (in the (i in 1:nresp) loop) and multiply each by a model by calling the function for (i in 1:nresp.
However, I am getting an error
Error in draws[j, ] <- rnorm(n = nresp, coef.mu[j], coef.sd[j]) :
incorrect number of subscripts on matrix
I presume if is something to do with the for loop, but I am a complete n00b so have no idea how to debug.
Please help!
Thanks in advance community!