这可能是因为您的sex
变量被编码为 acharacter
而不是 a factor
。
只需sex
在运行模型之前转换为因子就可以解决问题:
panel_data$sex <- factor(panel_data$sex)
这是一个可重现的示例来说明这个棘手的msm
包行为:
让我们首先在数据集上创建一个性别变量cav
为character
( sex.chr
) 和factor
( sex.fct
)
library(msm)
library(dplyr)
cav2 <-
cav %>%
mutate(
sex.chr = ifelse(sex == 1, 'M', 'F'),
sex.fct = factor(sex.chr)
)
我们也必须定义初始qmatrix
值:
twoway4.q <- rbind(c(-0.5, 0.25, 0, 0.25), c(0.166, -0.498, 0.166, 0.166),
c(0, 0.25, -0.5, 0.25), c(0, 0, 0, 0))
如果您使用as covariate的character
版本,您将得到两个协变量的相同结果(协变量基本上被忽略)sex
cav.msm.chr <- msm( state ~ years, subject = PTNUM, data = cav2,
qmatrix = twoway4.q, deathexact = 4, covariates = ~ sex.chr,
control = list ( trace = 2, REPORT = 1 ) )
qmatrix.msm(cav.msm.chr, covariates = list(sex.chr = "M"))
State 1 State 2 State 3
State 1 -0.17747 (-0.19940,-0.15795) 0.13612 ( 0.11789, 0.15718) 0
State 2 0.21992 ( 0.16100, 0.30040) -0.60494 (-0.70972,-0.51563) 0.33409 ( 0.26412, 0.42261)
State 3 0 0.12913 ( 0.07728, 0.21578) -0.41050 (-0.52552,-0.32065)
State 4 0 0 0
State 4
State 1 0.04135 ( 0.03245, 0.05268)
State 2 0.05092 ( 0.01808, 0.14343)
State 3 0.28137 ( 0.21509, 0.36808)
State 4 0
qmatrix.msm(cav.msm.chr, covariates = list(sex.chr = "F"))
State 1 State 2 State 3
State 1 -0.17747 (-0.19940,-0.15795) 0.13612 ( 0.11789, 0.15718) 0
State 2 0.21992 ( 0.16100, 0.30040) -0.60494 (-0.70972,-0.51563) 0.33409 ( 0.26412, 0.42261)
State 3 0 0.12913 ( 0.07728, 0.21578) -0.41050 (-0.52552,-0.32065)
State 4 0 0 0
State 4
State 1 0.04135 ( 0.03245, 0.05268)
State 2 0.05092 ( 0.01808, 0.14343)
State 3 0.28137 ( 0.21509, 0.36808)
State 4 0
但是使用阶乘版本sex
会给你预期的结果
cav.msm.fct <- msm( state ~ years, subject = PTNUM, data = cav2,
qmatrix = twoway4.q, deathexact = 4, covariates = ~ sex.fct,
control = list ( trace = 2, REPORT = 1 )
qmatrix.msm(cav.msm.fct, covariates = list(sex.fct = "M"))
State 1 State 2
State 1 -1.234e-01 (-1.750e-01,-8.693e-02) 7.667e-02 ( 4.630e-02, 1.270e-01)
State 2 2.838e-01 ( 1.139e-01, 7.075e-01) -6.435e-01 (-1.115e+00,-3.714e-01)
State 3 0 1.416e-01 ( 1.852e-02, 1.083e+00)
State 4 0 0
State 3 State 4
State 1 0 4.668e-02 ( 2.727e-02, 7.989e-02)
State 2 3.597e-01 ( 1.804e-01, 7.170e-01) 1.938e-05 ( 3.702e-66, 1.014e+56)
State 3 -8.207e-01 (-1.587e+00,-4.244e-01) 6.791e-01 ( 3.487e-01, 1.323e+00)
State 4 0
qmatrix.msm(cav.msm.fct, covariates = list(sex.fct = "F"))
State 1 State 2 State 3
State 1 -0.17747 (-0.19940,-0.15795) 0.13612 ( 0.11789, 0.15718) 0
State 2 0.21992 ( 0.16100, 0.30040) -0.60494 (-0.70972,-0.51563) 0.33409 ( 0.26412, 0.42261)
State 3 0 0.12913 ( 0.07728, 0.21578) -0.41050 #=(-0.52552,-0.32065)
State 4 0 0 0
State 4
State 1 0.04135 ( 0.03245, 0.05268)
State 2 0.05092 ( 0.01808, 0.14343)
State 3 0.28137 ( 0.21509, 0.36808)
State 4 0
```