I came across this example
library(mtcars)
set.seed(17)
cv.error.10 = rep(0,10)
for (i in 1:10){
glm.fit = glm(mpg∼poly(horsepower ,i),data=Auto)
cv.error.10[i] = cv.glm(Auto,glm.fit,K=10)$delta[1]
}
cv.error.10
[1] 24.21 19.19 19.31 19.34 18.88 19.02 18.90 19.71 18.95 19.50
I have been trying to pick up purrr
and modelr
. This seemed like a good example to try to replicate as it includes both a loop and cross validation. How would I convert this code to something more tidy verse like?
Update
With the below suggestions, this is where the code is at
data(mtcars)
cv_mtcars = mtcars %>%
crossv_kfold(k = 5)
cv_models = cv_mtcars %>%
mutate(model = map(train, ~lm(mpg ~ hp, data = .)),
rmse_all_models = map2_dbl(model, test, ~rmse(.x, .y)))
print(cv_models)
What I would like to do is repeat this for increasing polynomials of hp
such as hp^2
, hp^3
etc. I am guessing there is a purr
way to do this.
Update 2
Here is an example of the un-iterated code
data(mtcars)
cv_mtcars = mtcars %>%
crossv_kfold(k = 5)
cv_models = cv_mtcars %>%
mutate(model1 = map(train, ~lm(mpg ~ hp, data = .)),
model2 = map(train, ~lm(mpg ~I(hp^2), data = .)),
model3 = map(train, ~lm(mpg ~I(hp^3), data = .)),
model4 = map(train, ~lm(mpg ~I(hp^4), data = .)),
model5 = map(train, ~lm(mpg ~I(hp^5), data = .)),
model6 = map(train, ~lm(mpg ~I(hp^6), data = .)),
rmse_all_models1 = map2_dbl(model1, test, ~rmse(.x, .y)),
rmse_all_models2 = map2_dbl(model2, test, ~rmse(.x, .y)),
rmse_all_models3 = map2_dbl(model3, test, ~rmse(.x, .y)),
rmse_all_models4 = map2_dbl(model4, test, ~rmse(.x, .y)),
rmse_all_models5 = map2_dbl(model5, test, ~rmse(.x, .y)),
rmse_all_models6 = map2_dbl(model6, test, ~rmse(.x, .y)))
print(cv_models)