当我在R中运行二项式回归时,使用由三个级别“更高”,“中间”和“更低”组成的独立因子变量,我想使用relevel
更改参考类别我得到此错误:
“Error in relevel.ordered(cbsnivcat3, "Lower") :
'relevel' only for factors”
我已经检查过cbsnivcat3是否是一个因子
> is.factor(data$cbsnivcat3)
[1] TRUE
> levels(data$cbsnivcat3)
[1] "Higher" "Middle" "Lower"
> t1m4=glm(tertiary ~ relevel(cbsnivcat3, "Lower") , family = binomial, data = data)
Error in relevel.ordered(cbsnivcat3, "Lower") :
'relevel' only for factors
但与factor
glm(tertiary ~ factor(cbsnivcat3) , family = binomial, data = data)
相同的是oke。
MQ1:导致错误的原因是,我做错了什么?
提前感谢提示,命令和解决方案
STR(数据)
$ cbsnivcat3 : Ord.factor w/ 3 levels "Higher"<"Middle"<..: 1 1 1 1 1 1 1 1 1 1 ...
$ tertiary : num 0 0 1 1 1 1 0 1 0 0 ...
答案 0 :(得分:3)
cbsnivcat3
是一个有序因子,因此relevel
无效。您可以做的是将其改为普通因素:
cbsnivcat3 <- factor(cbsnivcat3, levels=c("Lower","Middle","Higher"))
答案 1 :(得分:1)
试试这个
df <- data.frame(y=sample(c(0,1), size=100,replace=T),x1=rep(c('a','b','c'),100), x2=1:100)
summary(glm(y~x1+x2,data=df))
df$x1 <- relevel(df$x1, ref='b')
summary(glm(y~x1+x2,data=df))
df$x1 <- relevel(df$x1, ref='c')
summary(glm(y~x1+x2,data=df))