eveyone. I am trying to run multinomial logit, however, I am encountering with problem. Bellow I will attach my code and the results, which gives me error - Error in t(betas) %*% X : non-conformable arguments. I tried to use advises from previous question from this website but it is not working. Hence, I would really appreciate if anyone looks my code and suggests what I should do.
> # Set seed for reproducibility
> set.seed(123)
> # Number of individuals (consumers)
> N <- 500
> # Number of mobile phone models (J)
> J <- 4 # Assuming 4 models: iPhone, Samsung, Google Pixel, and Other
> # Number of individual-alternative-specific characteristics (K)
> K <- 2 # Distance and liking the logo
> # Simulate individual characteristics
> distance <- runif(N, min = 1, max = 10) # Random distance values
> like_logo <- sample(c(0, 1), size = N, replace = TRUE) # Binary liking the logo
> # Simulate true coefficients (you can adjust these based on the story)
> true_beta <- c(0.5, -0.2, 0.8) # Intercept, Distance, Logo
> # Simulate utility for each alternative (linear predictor)
> utility <- matrix(0, nrow = N, ncol = J)
> for (j in 1:J) {
+ utility[, j] <- true_beta[1] + true_beta[2] * distance + true_beta[3] * like_logo
+ }
> # Gumbel errors
> errors <- matrix(rgumbel(N * J, 0, 1), nrow = N, ncol = J)
> # Add Gumbel errors to utility
> utility <- utility + errors
> # Calculate choice probabilities using the multinomial logit formula
> probabilities <- exp(utility) / rowSums(exp(utility))
> # Simulate choices based on probabilities
> choices <- apply(probabilities, 1, function(x) sample(1:J, size = 1, prob = x))
> # Create a data frame with simulated data
> simulated_data <- data.frame(
+ Choice = factor(choices, levels = 1:J),
+ Distance = distance,
+ LikeLogo = like_logo
+ )
> # The log likelihood function
> cond_logit <- function(betas, data) {
+ X <- model.matrix(Choice ~ Distance + LikeLogo, data)
+ utilities <- t(betas) %*% X # Transpose betas before multiplication
+ utilities_matrix <- matrix(utilities, ncol = J, byrow = TRUE)
+
+ exp_utilities <- exp(utilities_matrix)
+ probabilities <- exp_utilities / rowSums(exp_utilities)
+
+ chosen_alternative <- as.numeric(data$Choice)
+ llhood <- sum(log(probabilities[cbind(chosen_alternative, 1:N)]))
+
+ return(-llhood) # Return negative log-likelihood for minimization
+ }
> guess <- c(0, 0) # initial guess
> # Maximizing log-likelihood
> result <- optim(par = guess, fn = cond_logit, data = simulated_data, control = list(fnscale = -1), hessian = TRUE, method = "BFGS")
**Error in t(betas) %*% X : non-conformable arguments**
--- how can I adress this issue? I would really appreciate your help