我使用speedglm将GLM与数据相匹配。当我直接调用函数时,代码按预期工作,但是当我创建一个符合模型的函数时,我会得到一个错误,即找不到参数。
变量(在下面的示例中是w)显然存在于函数的范围内,但似乎该变量只在速度函数中稍后才计算,其中w不再可用,所以我认为。这就是我开始质疑我目前对R.
在创建函数时,是否犯了错误,是否使用了一些奇怪的技巧来对打破常规(?)的变量(源代码这里)进行范围分析?逻辑还是我对R函数是如何工作的有错误的理解?
我正在尝试理解这种行为,并修复我的train_glm函数,使它能够与速度和重量一起工作。
米维
library(speedglm)
# works as expected
m1 <- speedglm(wt ~ cyl, data = mtcars, weights = mtcars$wt)
# define a small helper function that just forwards its arguments
train_glm <- function(f, d, w) {
speedglm(formula = f, data = d, weights = w)
}
# does not work
m <- train_glm(wt ~ cyl, d = mtcars, w = mtcars$wt)
#> Error in eval(extras, data, env) : object 'w' not found更奇怪的是,如果我更改代码,我发现
# removing the weights as a base case -> WORKS
train_glm3 <- function(f, d) {
speedglm(formula = f, data = d)
}
m3 <- train_glm3(wt ~ cyl, d = mtcars)
# works
# hardcoding the weights inside the function -> BREAKS
train_glm4 <- function(f, d) {
speedglm(formula = f, data = d, weights = d$wt)
}
m4 <- train_glm4(wt ~ cyl, d = mtcars)
# Error in eval(extras, data, env) : object 'd' not found
# creating a new dataset and hardcoding the weights inside the function
# but using the name of the dataset at the highest environment -> WORKS
train_glm5 <- function(f, d) {
speedglm(formula = f, data = d, weights = mtcars2$wt)
}
mtcars2 <- mtcars
m5 <- train_glm5(wt ~ cyl, d = mtcars2)
# works发布于 2022-10-10 06:29:01
解决方案(感谢@Mike的提示)是通过使用这个答案提供的解决方案或使用类似于这样的do.call来计算代码:
library(speedglm)
train_glm_docall <- function(f, d, w) {
do.call(
speedglm,
list(
formula = f,
data = d,
weights = w
)
)
}
m2 <- train_glm_docall(f = wt ~ cyl, d = mtcars, w = mtcars$wt)
class(m2)
#> [1] "speedglm" "speedlm"https://stackoverflow.com/questions/73989875
复制相似问题