R:在函数中包装多项式回归的问题
R: Problems of wrapping polynomial regression in a function
当我做多项式回归时,我试图将不同次数的多项式拟合到一个列表中,所以我将 glm 包装到一个函数中:
library(MASS)
myglm <- function(dop) {
# dop: degree of polynomial
glm(nox ~ poly(dis, degree = dop), data = Boston)
}
不过,我想可能存在一些与懒惰求值相关的问题。模型的度数是参数dop而不是具体的数字。
r$> myglm(2)
Call: glm(formula = nox ~ poly(dis, degree = dop), data = Boston)
Coefficients:
(Intercept) poly(dis, degree = dop)1 poly(dis, degree = dop)2
0.5547 -2.0031 0.8563
Degrees of Freedom: 505 Total (i.e. Null); 503 Residual
Null Deviance: 6.781
Residual Deviance: 2.035 AIC: -1347
当我使用此模型进行交叉验证时,出现错误:
>>> cv.glm(Boston, myglm(2))
Error in poly(dis, degree = dop) : object 'dop' not found
那么我该如何解决这个问题呢?
Quosures, quasiquotation, and tidy evaluation 在这里很有用:
library(MASS)
library(boot)
library(rlang)
myglm <- function(dop) {
eval_tidy(quo(glm(nox ~ poly(dis, degree = !! dop), data = Boston)))
}
cv.glm(Boston, myglm(2))
当我做多项式回归时,我试图将不同次数的多项式拟合到一个列表中,所以我将 glm 包装到一个函数中:
library(MASS)
myglm <- function(dop) {
# dop: degree of polynomial
glm(nox ~ poly(dis, degree = dop), data = Boston)
}
不过,我想可能存在一些与懒惰求值相关的问题。模型的度数是参数dop而不是具体的数字。
r$> myglm(2)
Call: glm(formula = nox ~ poly(dis, degree = dop), data = Boston)
Coefficients:
(Intercept) poly(dis, degree = dop)1 poly(dis, degree = dop)2
0.5547 -2.0031 0.8563
Degrees of Freedom: 505 Total (i.e. Null); 503 Residual
Null Deviance: 6.781
Residual Deviance: 2.035 AIC: -1347
当我使用此模型进行交叉验证时,出现错误:
>>> cv.glm(Boston, myglm(2))
Error in poly(dis, degree = dop) : object 'dop' not found
那么我该如何解决这个问题呢?
Quosures, quasiquotation, and tidy evaluation 在这里很有用:
library(MASS)
library(boot)
library(rlang)
myglm <- function(dop) {
eval_tidy(quo(glm(nox ~ poly(dis, degree = !! dop), data = Boston)))
}
cv.glm(Boston, myglm(2))