Last active
September 9, 2022 16:58
-
-
Save juanchiem/d8ac580de28474b40962c66b8ea27f7d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(purrr) | |
library(tidyverse) | |
newdata=data.frame(Sepal.Length=seq(4, 8, by=.5)) | |
# newdata$Sepal.Length | |
fitted_models <- iris %>% | |
nest(data = -Species) %>% | |
mutate(fit = map(data, ~ lm(Petal.Length ~ Sepal.Length + I(Sepal.Length^2), data = .x)), | |
# fitted = map(fit, "fitted.values"), | |
predicted_Petal.Length= map(fit, ~ predict(.x, newdata = newdata)) | |
) %>% | |
unnest(cols = c(predicted_Petal.Length)) %>% | |
select(Species, predicted_Petal.Length) %>% | |
mutate(Sepal.Length=rep(newdata$Sepal.Length, 3)) %>% | |
rename(Petal.Length= predicted_Petal.Length) | |
fitted_models %>% | |
ggplot()+ | |
aes(Sepal.Length, Petal.Length, col=Species)+ | |
geom_point(data=iris, aes(Sepal.Length, Petal.Length, col=Species))+ | |
geom_line() + | |
geom_point(data=fitted_models %>% | |
group_by(Species) %>% | |
slice(which.max(Petal.Length)), | |
col="black") | |
fitted_models %>% | |
group_by(Species) %>% | |
slice(which.max(Petal.Length)) | |
Author
juanchiem
commented
Sep 9, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment