4

I'm trying to fit a logistic regression model using all predictors as a polynomial model. I've tried doing this but didn't work:

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

I'm using the built in dataset:

train_data = MASS::Pima.tr

What's the correct way to do this?

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • So can you write out the actual model you are trying to fit? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 25 '21 at 01:39
  • Added the dataset I'm using which is built-in in R. It has 7 predictors and I'm using `type` as the response. –  Jul 25 '21 at 01:43
  • 1
    I don't think it can be done using `.` . You probably will need to build the formula you want e.g. `fm <- reformulate(paste0("poly(", setdiff(names(train_data), "type"), ", 2)"), "type"); glm(fm, data=train_data, family=binomial)`. – Ritchie Sacramento Jul 25 '21 at 02:33

1 Answers1

3

There's not really a way to do that with the . syntax. You'll need to explictly build the formula yourself. You can do this with a helper function

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)
MrFlick
  • 195,160
  • 17
  • 277
  • 295