3

I have created simulated data for a mixed logit model. It involves N anglers taking two trips, each of which can be to one of two sites. Here is the code to create the simulated data:

library(data.table)
library(mlogit)

### Angler choice probabilities for site a
N <- 1e4
beta <- rnorm(N, mean = 0.5)
val <- runif(N)
p <- exp(1 + beta*val)/(1+ exp(1 + beta*val))

### Choice for trip 1
Y11 <- rbinom(N, 1, p)
Y10 <- 1 - Y11

### Choice for trip 2
Y21 <- rbinom(N, 1, p)
Y20 <- 1 - Y21

### Data set
id <- as.character(1:N)
sim <- data.table(angler = rep(id, 4), 
                  trip = paste(id, rep(1:2, each = 2*N), sep = "_"),
                  site = c(rep(letters[1:2], each = N),
                           rep(letters[1:2], each = N)),
                  is_choice = as.logical(c(Y11, Y10, Y21, Y20)),
                  term = c(val, rep(0, N), val, rep(0, N)))
sim[, term2 := ifelse(site == "a", 1, 0)]

When I run mlogit, I get the following error:

> mlogit(is_choice ~ 1, sim, shape = "long", alt.var = "site", chid.var = "trip", id.var = "angler")
Error in str2lang(x) : <text>:2:0: unexpected end of input
1: . ~   . |  
  ^

I can run examples from the vignette, so there doesn't seem to be an installation issue.

What am I fouling up? Thanks!

Charlie
  • 2,801
  • 3
  • 26
  • 27

1 Answers1

2

This problem can be solved by using data.frame, not data.table.

sim2 <- as.data.frame(sim)
mlogit(is_choice ~ 1, sim2, shape = "long", alt.var = "site", chid.var = "trip", id.var = "angler")

Call:
mlogit(formula = is_choice ~ 1, data = sim2, shape = "long",     alt.var = "site", chid.var = "trip", id.var = "angler", method = "nr")

Coefficients:
(Intercept):b  
      -1.1595 
Park
  • 14,771
  • 6
  • 10
  • 29