【问题标题】:mlogit gives error: the two indexes don't define unique observationsmlogit 给出错误:这两个索引没有定义唯一的观察结果
【发布时间】:2020-09-02 13:47:14
【问题描述】:

我的名为 longData 的数据框看起来像:

  ID Set Choice Apple Microsoft IBM Google Intel HewlettPackard Sony Dell Yahoo Nokia
1  1   1      0     1         0   0      0     0              0    0    0     0     0
2  1   2      0     0         1   0      0     0              0    0    0     0     0
3  1   3      0     0         0   1      0     0              0    0    0     0     0
4  1   4      1     0         0   0      1     0              0    0    0     0     0
5  1   5      0     0         0   0      0     0              0    0    0     0     1
6  1   6      0    -1         0   0      0     0              0    0    0     0     0

我正在尝试通过以下方式运行 mlogit:

logitModel = mlogit(Choice ~ Apple+Microsoft+IBM+Google+Intel+HewlettPackard+Sony+Dell+Yahoo+Nokia | 0, data = longData, shape = "long")

它给出了以下错误:

Error in dfidx::dfidx(data = data, dfa$idx, drop.index = dfa$drop.index,  : 
  the two indexes don't define unique observations

找了一段时间后,我发现这个错误是由dfidx 给出的,如here 所示:

z <- data[, c(posid1[1], posid2[1])]
if (nrow(z) != nrow(unique(z)))
    stop("the two indexes don't define unique observations")

但是在调用以下代码时,它运行时没有错误,并给出了两个 idx 的名称,它们能够唯一地识别数据帧中的一行:

dfidx(longData)$idx

这给出了预期的输出:

~~~ indexes ~~~~
   ID Set
1   1   1
2   1   2
3   1   3
4   1   4
5   1   5
6   1   6
7   1   7
8   1   8
9   1   9
10  1  10
indexes:  1, 2 

那么我做错了什么,我看到了一些相关的问题12,但找不到我缺少的东西。

【问题讨论】:

    标签: r mlogit


    【解决方案1】:

    您的示例似乎来自这里:https://docs.displayr.com/wiki/MaxDiff_Analysis_Case_Study_Using_R

    代码似乎过时了,我记得它对我有用,但现在不行了。

    错误消息是有效的,因为每对 (ID, Set) 出现多次,每个替代项出现一次。

    但这是可行的:

    # there will be complaint that choice can't be coerced to logical otherwise
    longData$Choice <- as.logical(longData$Choice)
    # create alternative number (nAltsPerSet is 5 in this example)
    longData$Alternative <- 1+( 0:(nrow(longData)-1) %% nAltsPerSet)
    # define dataset
    mdata <- mlogit.data(data=longData,shape="long", choice="Choice",alt.var="Alternative",id.var="ID")
    # model
    logitModel = mlogit(Choice ~ Microsoft+IBM+Google+Intel+HewlettPackard+Sony+Dell+Yahoo+Nokia | 0,
                        data = mdata
    )
    
    summary(logitModel)
    
    

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 2022-01-18
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多