Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels): factor X has new levels

前端 未结 1 801
执念已碎
执念已碎 2021-01-14 15:42

I did a logistic regression:

 EW <- glm(everwrk~age_p + r_maritl, data = NH11, family = \"binomial\")

Moreover, I want to predict

相关标签:
1条回答
  • 2021-01-14 16:11

    tl;dr it looks like you have some levels in your factor that are not represented in your data, that get dropped from the factors used in the model. In hindsight this isn't terribly surprising, since you won't be able to predict responses for these levels. That said, it's mildly surprising that R doesn't do something nice for you like generate NA values automatically. You can solve this problem by using levels(droplevels(NH11$r_maritl)) in constructing your prediction frame, or equivalently EW$xlevels$r_maritl.

    A reproducible example:

    maritl_levels <- c( "0 Under 14 years", "1 Married - spouse in household", 
      "2 Married - spouse not in household", "3 Married - spouse in household unknown", 
      "4 Widowed", "5 Divorced", "6 Separated", "7 Never married", "8 Living with partner", 
     "9 Unknown marital status")
    set.seed(101)
    NH11 <- data.frame(everwrk=rbinom(1000,size=1,prob=0.5),
                     age_p=runif(1000,20,50),
                     r_maritl = sample(maritl_levels,size=1000,replace=TRUE))
    

    Let's make a missing level:

    NH11 <- subset(NH11,as.numeric(NH11$r_maritl) != 3)
    

    Fit the model:

    EW <- glm(everwrk~r_maritl+age_p,data=NH11,family=binomial)
    predEW <- with(NH11,
      expand.grid(r_maritl=levels(r_maritl),age_p=mean(age_p,na.rm=TRUE)))
    predict(EW,newdata=predEW)
    

    Success!

    Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : factor r_maritl has new levels 2 Married - spouse not in household

    predEW <- with(NH11,
               expand.grid(r_maritl=EW$xlevels$r_maritl,age_p=mean(age_p,na.rm=TRUE)))
    predict(EW,newdata=predEW)
    
    0 讨论(0)
提交回复
热议问题