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?