Skip to content

Instantly share code, notes, and snippets.

@juanchiem
Last active September 9, 2022 16:58
Show Gist options
  • Save juanchiem/d8ac580de28474b40962c66b8ea27f7d to your computer and use it in GitHub Desktop.
Save juanchiem/d8ac580de28474b40962c66b8ea27f7d to your computer and use it in GitHub Desktop.
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))
@juanchiem
Copy link
Author

imagen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment