model.frame.default中的错误(Terms,newdata,na.action = na.action,xlev = object $ xlevels):因子X有新的级别

时间:2017-08-20 16:50:18

标签: r logistic-regression

我做了逻辑回归:

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

此外,我想为everwrk的每个级别预测r_maritl

r_maritl具有以下级别:

levels(NH11$r_maritl)
 "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"  

所以我做了:

predEW <- with(NH11,
expand.grid(r_maritl = 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"),
age_p = mean(age_p,na.rm = TRUE)))

cbind(predEW, predict(EW, type = "response",
                        se.fit = TRUE, interval = "confidence",
                        newdata = predEW))

问题是我收到以下回复:

  

model.frame.default中的错误(条款,newdata,na.action = na.action,xlev =     object $ xlevels):因子r_maritl有新的等级0未满14岁,已婚        - 家庭未知的配偶

示例数据:

str(NH11$age_p)
num [1:33014] 47 18 79 51 43 41 21 20 33 56 ...

str(NH11$everwrk)
Factor w/ 2 levels "2 No","1 Yes": NA NA 2 NA NA NA NA NA 2 2 ...

str(NH11$r_maritl)
Factor w/ 10 levels "0 Under 14 years",..: 6 8 5 7 2 2 8 8 8 2 ...

1 个答案:

答案 0 :(得分:3)

tl; dr 看起来您的因子中有一些未在数据中表示的级别,这些级别会从模型中使用的因子中删除。事后看来,这并不令人惊讶,因为您无法预测这些级别的响应。也就是说,它并不是很令人惊讶的是,R并没有为你做一些好事,比如自动生成NA值。您可以在构建预测帧时使用levels(droplevels(NH11$r_maritl))或等效EW$xlevels$r_maritl来解决此问题。

可重现的例子:

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))

让我们失去一个水平:

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

适合模特:

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)

成功!

  

model.frame.default中的错误(条款,newdata,na.action = na.action,xlev = object $ xlevels):        因素r_maritl有新的等级2已婚 - 配偶不在家庭

predEW <- with(NH11,
           expand.grid(r_maritl=EW$xlevels$r_maritl,age_p=mean(age_p,na.rm=TRUE)))
predict(EW,newdata=predEW)