user20380762
user20380762

Reputation: 25

Error in using mlogit function: "replacement has 8 rows, data has 9"

I am trying to estimate a simple multinomial logit model. The utility of a product is given by:

U_{ij}=\beta⋅price_{ij}​+fixed_effect_j​+ϵ_{ij}.

I have data which contains the choices made by individuals i, across products j. (Each product may not be sampled on each occasion, and the number of products sampled may vary. I observe the sampled products and the product which is selected amongst the sampled products). My aim is to estimate \beta and the fixed_effects for each product.

I believe I can use the following code for this:

library(mlogit)
# Example data (already in long format)
temp <- data.table(
  session_id = c(1, 1, 2, 2, 2, 3, 3, 3, 3),
  object_id = c(1, 2, 1, 2, 3, 1, 2, 3, 4),
  chosen = c(0, 1, 1, 0, 0, 0, 1, 0, 0),
  price = c(10, 20, 30, 25, 20, 15, 30, 25, 10)
)

# Ensure consistent data types
temp[, session_id := as.integer(session_id)]
temp[, object_id := as.integer(object_id)]
temp[, chosen := as.integer(chosen)]
temp[, price := as.numeric(price)]

# Print the data to verify
print("Original data:")
print(temp)

# Check the dimensions
print("Dimensions of temp:")
print(dim(temp))

# Fit the multinomial logit model using mlogit
formula <- chosen ~ 0 | object_id + price
model <- mlogit(formula, data = temp, choice = "chosen", shape = "long", alt.var = "object_id", id.var = "session_id")

but I get the error:

model <- mlogit(formula, data = temp, choice = "chosen", shape = "long", alt.var = "object_id", id.var = "session_id")

Error in $<-.data.frame(x, name, value) : replacement has 8 rows, data has 9

I do not know what is causing this, nor does ChatGPT. Please help!

Upvotes: 1

Views: 66

Answers (0)

Related Questions