1

I have created an artificial data for mlogit with each person given 4 choices in two sets. However I am getting impossible to coerce the choice variable to a logical error while trying to apply the model.

I have seen the following link but it is not solving my case. Not able to understand the reason properly. Can you please help.

R Mlogit Error in replacement rows and impossible to coerce choice variable to logical

My data looks like this :

enter image description here

Data I am using :

dput( df1 )
structure(list(Alternative = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), Choice = c(0L, 1L, 0L, 0L, 0L, 
0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 
0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 
0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 
1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L), A = c(0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, -1L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, -1L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, -1L, 0L, 0L), 
    B = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 
    0L, 0L, -1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L, 0L, 1L, 0L, 
    0L, 0L, -1L, 0L)), row.names = c(NA, -64L), class = "data.frame")

Code

model = mlogit( Choice ~ B + C + D + E + F + G + H + I | 0, data = df1, 
               
               alt.var = 'Alternative', 
               
               shape = "long")

Error :

Error in dfidx::dfidx(data = data, dfa$idx, drop.index = dfa$drop.index,  : 
  impossible to coerce the choice variable to a logical
Soumya Boral
  • 1,191
  • 14
  • 28
  • Before running the model, try transforming the `Choice` column in `df1` from `integer` to `logical`, via `as.logical()`. – Greg Jul 21 '21 at 19:26
  • Once I do it, I am getting the following error : `Error in if (abs(x - oldx) < ftol) { : missing value where TRUE/FALSE needed` – Soumya Boral Jul 21 '21 at 19:28
  • Did you try `library(tidyverse)` and `df1 <- df1 %>% mutate(Choice = as.logical(Choice))`? If you did that, and it still failed, then it looks like [`mlogit` is to blame](https://community.rstudio.com/t/mlogit-data-fails-for-latest-version-of-mlogit-package/23507). – Greg Jul 21 '21 at 19:31
  • 1
    Are _all_ these fields expected to be `logical`? – Greg Jul 21 '21 at 19:33
  • Yes I tried this. No all fields are not expected to be logical. They can stay numeric. – Soumya Boral Jul 21 '21 at 19:35
  • You could look at the dfidx function source code (around line 442) to reason about the error – Bill O'Brien Jul 21 '21 at 19:45

0 Answers0