gpt4 book ai didi

r - 在 R 中使用 mlogit 的级别错误

转载 作者:行者123 更新时间:2023-12-02 02:21:11 24 4
gpt4 key购买 nike

我在关卡上遇到了一些问题...运行以下命令:

library(mlogit)

panel.datasm = data.frame(
cbind(
round(runif(100, min=1, max=6)),
rep(1:20,each=5), runif(100, min=0, max=1),
runif(100, min=0, max=6),
runif(100, min=2, max=6) ,
runif(100, min=0, max=1),
runif(100, min=0, max=6),
runif(100, min=2, max=6) ))
names(panel.datasm) = c("choice", "id", "data_1991","data_1992",
"data_1993", "data2_1991", "data2_1992","data2_1993")


logit.data <- mlogit.data(panel.datasm, id = "id", choice = "choice",
varying= 3:5, shape = "wide", sep = "_")

不断收到错误 Error in Ops.factor(data[[choice]], alt) : level sets of factors are different

我也试过手动分配级别:

panel.datasm$id= factor(
panel.datasm$id,
levels = sort(as.character(unique(panel.datasm$id))) )

我已经尝试了很多东西,但无法弄清楚哪里出了问题。为了进行比较,请查看:

data("Electricity", package = "mlogit")
head(Electricity)
Electr <- mlogit.data(Electricity, id = "id", choice = "choice",
varying = 3:26, shape = "wide", sep = "")

据我所知,这与我的数据格式相同。这里发生了什么?我快结束了。

最佳答案

我相信我已经找到问题所在。您的 choice 变量和您的 alternative 变量应该相同。

如果您将 data.frame 的第一列更改为具有 1991:1993 之间的值,它将起作用。

panel.datasm = data.frame(
cbind(
sample(1991:1993, 100, replace=TRUE),
rep(1:20,each=5), runif(100, min=0, max=1),
runif(100, min=0, max=6),
runif(100, min=2, max=6) ,
runif(100, min=0, max=1),
runif(100, min=0, max=6),
runif(100, min=2, max=6) ))
names(panel.datasm) = c("choice", "id", "data_1991","data_1992",
"data_1993", "data2_1991", "data2_1992","data2_1993")


logit.data <- mlogit.data(panel.datasm, id = "id", choice = "choice",
varying= 3:5, shape = "wide", sep = "_")

结果:

head(logit.data)
choice id alt data data2 chid
1.1991 FALSE 1 1991 0.03540498 0.9726110 1
1.1992 FALSE 1 1992 5.85285278 2.7973798 1
1.1993 TRUE 1 1993 5.80795641 3.7360297 1
2.1991 TRUE 1 1991 0.59255235 0.2564928 2
2.1992 FALSE 1 1992 5.81443351 3.0820215 2
2.1993 FALSE 1 1993 2.11699854 5.4161634 2

如果您现在将它与电力 进行比较,区别就很明显了。请注意,选项是 1:4,每个选项的范围从 1 到 4。

head(Electricity)
choice id pf1 pf2 pf3 pf4 cl1 cl2 cl3 cl4 loc1 loc2 loc3 loc4 wk1 wk2 wk3 wk4
1 4 1 7 9 0 0 5 1 0 5 0 1 0 0 1 0 0 1
2 3 1 7 9 0 0 0 5 1 5 0 0 1 0 1 1 0 0
3 4 1 9 7 0 0 5 1 0 0 0 0 0 1 0 1 1 0
4 4 1 0 9 7 0 1 1 0 5 0 0 1 0 1 0 0 1
5 1 1 0 9 0 7 0 1 0 5 1 0 0 0 0 1 0 1
6 4 1 0 9 0 7 0 0 1 5 0 0 1 0 0 0 0 1

关于r - 在 R 中使用 mlogit 的级别错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8085837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com