0
$\begingroup$

I am trying to analyze some data from the Auto data set (from ISLR2). I am trying to fit a piecewise polynomial to the acceleration column. But every time I run my code, R throws this error:

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
factor cut(acceleration, 8) has new levels (7.98,10], (10,12], (12,14], (14,16], (16,18], (18,20], (20,22], (22,24]

I ran the code below, with some alterations for the Wage dataset for a 8 step piecewise fit, and it worked just fine. I wonder what I am doing wrong. Here is the code I have:

cv.steps <- c()
for (i in 2:10) {
  Auto$acc.cut <- cut(Auto$acceleration, i)
  glm.fit <- glm(mpg ~ acc.cut, data = Auto)
  cv.steps[i] <- cv.glm(Auto, glm.fit, K = 10)$delta[1]
}

#Plot to see the lowest value. 
plot(2:10, cv.steps[-1], xlab = "Number of Breaks", ylab = "CV Errors", type = "l")
lm.fit <- glm(mpg ~ cut(acceleration, 8), data = Auto)
alims <- range(Auto$acceleration)
agrid <- seq(from = alims[1], to = alims[2])
preds.a <- predict(lm.fit, data.frame(acceleration = agrid))
plot(mpg ~ acceleration, data = Auto,  col = "darkgrey")
$\endgroup$

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.