我有以下 R 代码:
library(geepack)
library(nlme)
data(dietox)
dietox$Cu <- as.factor(dietox$Cu)
mf <- Weight ~ Cu + Time
step1_func<- function(formula, data, id,family){
# Step 1: Initial estimation using GEE with `geepack::geeglm`
step1 <- geepack::geeglm(
formula,
family = family,
data = data,
id = id
)
return(step1)
}
step1_func(mf, data=dietox, id=Pig, family=poisson("identity"))
当我运行此程序时,我收到错误
Error in eval(extras, data, env) : object 'id' not found
。
当我使用
geepack::geeglm()
时,它工作得很好(尽管有一些警告)。
# This works!
geepack::geeglm(
mf,
family = poisson("identity"),
data = dietox,
id = Pig
)
这里有什么问题吗?有解决办法可以使这个工作吗?
注意
geeglm
使用NSE进行建模。我举一个简单的例子。下图:
fn1 <- function(data, x) get(substitute(x), data)
fn2 <- function(data, x) fn1(data, x)
fn1(head(iris), Species)
[1] setosa setosa setosa setosa setosa setosa
Levels: setosa versicolor virginica
fn2(head(iris), Species)
Error in get(substitute(x), data) : object 'x' not found
请注意,
fn2
会失败,即使它只是 fn1
的包装。
解决方法。您可以使用
do.call
或 as.call
+ eval
等。我建议使用 as.call
,因为输出包括对 match.call
的调用:
step1_func<- function(formula, data, id,family){
step1 <- as.call(list(quote(geepack::geeglm),
formula = formula,
family = substitute(family),
data = substitute(data), id = substitute(id)))|>
eval()
return(step1)
}