3

我有一堆模型我想通过 GLM 使用,所以我想把它们放在一个列表中,然后循环遍历列表。但是,以下代码会产生错误:

m1<- glm(target~total+tot_eit_h_h1+tot_both_h_h1, data=data, family='binomial')
m2<- glm(target~total+tot_both_h_h1, data=data, family='binomial')
models<- c(m1,m2)

这完美地工作:

predictions <- predict(m1, data, type='response')

此代码得出错误:

predictions <- predict(models[1], data, type='response')

Error in UseMethod("predict") : 
no applicable method for 'predict' applied to an object of class "list"
4

2 回答 2

4

尝试

models<- list(m1,m2)

predictions <- predict(models[[1]], data, type='response')

glm返回一个列表。运算符将该c列表“展平”为向量,以便与glm对象关联的函数无法在展平的向量上工作。作为一项规则,您不想用于c连接列表(即使您有时可以侥幸逃脱,如您的示例所示)。

于 2013-08-11T23:38:31.267 回答
3

您可以使用Map具有以下技巧的函数(以 mtcars 数据说明的示例):

dep<-list("mpg~","mpg~")  # list of dep variables which is same in both models
indep<-list("cyl","cyl+disp") #for model 1 includes cyl and for model 2 includes cyl and disp
prediction<-Map(function(x,y) predict(lm(as.formula(paste(x,y)),data=mtcars)),dep,indep)

> prediction[[1]]
          Mazda RX4       Mazda RX4 Wag          Datsun 710      Hornet 4 Drive   Hornet Sportabout 
           20.62984            20.62984            26.38142            20.62984            14.87826 
            Valiant          Duster 360           Merc 240D            Merc 230            Merc 280 
           20.62984            14.87826            26.38142            26.38142            20.62984 
          Merc 280C          Merc 450SE          Merc 450SL         Merc 450SLC  Cadillac Fleetwood 
           20.62984            14.87826            14.87826            14.87826            14.87826 
Lincoln Continental   Chrysler Imperial            Fiat 128         Honda Civic      Toyota Corolla 
           14.87826            14.87826            26.38142            26.38142            26.38142 
      Toyota Corona    Dodge Challenger         AMC Javelin          Camaro Z28    Pontiac Firebird 
           26.38142            14.87826            14.87826            14.87826            14.87826 
          Fiat X1-9       Porsche 914-2        Lotus Europa      Ford Pantera L        Ferrari Dino 
           26.38142            26.38142            26.38142            14.87826            20.62984 
      Maserati Bora          Volvo 142E 
           14.87826            26.38142 
于 2013-08-12T00:29:13.727 回答