函数内的 lapply、glm 和 speedglm:缺少参数 "data",没有默认值

lapply, glm, and speedglm inside a function: argument "data" is missing, with no default

我正在使用 mtcars 数据来说明我的问题。以下代码适用于 glm。它通过将 vlist 中的每个变量添加到 glm(vs ~ mpg, family = binomial(), data = mtcars 的模型中来生成新模型。

check_glm <- function(crude, vlist, data, ...){
  a <- glm(crude, data = data, family = binomial())
  lapply(vlist, function(x) update(a, as.formula(paste0(". ~ . +", x))))
}
check_glm(crude = "vs ~ mpg", vlist = c("am", "hp"), data = mtcars)

但是,当我将 glm 替换为 speedglm 时,

library(speedglm)
check_speedglm <- function(crude, vlist, data, ...){
  a <- speedglm(crude, data = data, family = binomial())
  lapply(vlist, function(x) update(a, as.formula(paste0(". ~ . +", x))))
}
check_speedglm(crude = "vs ~ mpg", vlist = c("am", "hp"), data = mtcars)

我得到了:

Error in model.frame.default(formula = vs ~ mpg + am, data = data, drop.unused.levels = TRUE) : argument "data" is missing, with no default.

我认为问题出在 lapply 行,但我无法找到解决方案。解决此问题的任何建议将不胜感激。

从本质上讲,您正在混淆可能彼此不兼容的包方法。尽管它们共享相同的名称,但这两种方法都来自不同的包,因此不同的作者出于不同的目的并输出不同的对象(glm class 与 speedglm class 这可能是S3 与 S4 对象)。

具体来说,glm 方法是 stats 包中 R 标准库的一部分,它与其相关的 stats 方法 update 一起工作。

根据 update 文档,

update will update and (by default) re-fit a model. It does this by extracting the call stored in the object, updating the call and (by default) evaluating that call. 

主要参数:

object, x: An existing fit from a model function such as lmglm and many others

因此,如果 speedglm 存储调用以捕获公式、数据和其他参数,并且类似于 return 对象结构,如 glm(继承自 lm class),那么 update 就可以了。


要解决此问题,请考虑通过使用 lapply 的迭代模型调用动态构建 formula 来执行 update 所做的事情。这将适用于两种方法,因为每种方法都使用 formula 对象。

library(speedglm) 

check_speedglm <- function(crude, vlist, data, ...){ 
   lapply(seq_along(vlist), function(i)
       speedglm(as.formula(paste(crude, "+", paste(vlist[1:i], collapse=" + "))), 
                data = data, family = binomial()) 
   )
} 

check_speedglm(crude = "vs ~ mpg", vlist = c("am", "hp"), data = mtcars)