如何使用“.”拟合所有预测变量的多项式模型在 R?

How to fit polynomial model of all predictors using "." in R?

我正在尝试使用所有预测变量作为多项式模型来拟合逻辑回归模型。我试过这样做但没有成功:

poly_model = glm(type~ poly(., 2), data=train_data, family=binomial)

我正在使用内置数据集:

train_data = MASS::Pima.tr

正确的做法是什么?

使用 . 语法确实没有办法做到这一点。您需要自己明确构建公式。您可以使用辅助函数

get_formula <- function(resp) {
  reformulate(
    sapply(setdiff(names(train_data), resp), function(x) paste0("poly(", x, ", 2)")),
    response = resp
  )
}


model <- get_formula("type")
model
# type ~ poly(npreg, 2) + poly(glu, 2) + poly(bp, 2) + poly(skin, 
#     2) + poly(bmi, 2) + poly(ped, 2) + poly(age, 2)
glm(model, data=train_data, family=binomial)