Using predict with svyglm

对着背影说爱祢 提交于 2019-12-10 20:38:35

问题


I have found some odd behavior with predict and the svyglm object from the survey package. If your newdata in predict has a factor/character with one level it spits out error:

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
contrasts can be applied only to factors with 2 or more levels

This error makes sense if I was putting a one level variable as the predictor for a model, but for newdata I don't see the problem.

With regular glm this works fine.

MRE:

library(survey)

data(api)

dstrat<-svydesign(id=~1,strata=~stype, weights=~pw, data=apistrat, fpc=~fpc)

svymodel <- svyglm(api00~sch.wide,design=dstrat)
# errors
predict(svymodel, data.frame(sch.wide=rep("No",10)))

regmodel <- glm(api00~sch.wide,data=apistrat)
# works
predict(regmodel,data.frame(sch.wide=rep("No",10)))

I find that it works if I hack the levels of the factor, but this shouldn't be necessary:

svymodel <- svyglm(api00~sch.wide,design=dstrat)

predict(svymodel, data.frame(sch.wide=factor(rep("No",10),
                                             levels = c("No","random phrase"))))

Am I misunderstanding something or is this an issue with the survey package?


回答1:


You aren't putting a factor in newdata; you're putting a character string in. You should put in a factor with the same set of levels as the factor used to fit the model (not some random phrase) -- that's the only way the design matrix makes sense.

predict(svymodel, data.frame(sch.wide=factor(rep("No",10),levels=c("No","Yes"))))

predict.lm recovers the factor levels from the fitted object (I don't remember this being around in 2002, but I might be wrong). You can use that approach to automate:

predict(svymodel, data.frame(sch.wide=factor(rep("No",10),levels=svymodel$xlevels$sch.wide)))

and I'll put that on the list of things to do for the package.



来源:https://stackoverflow.com/questions/40472586/using-predict-with-svyglm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!