You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.0KB

  1. library(tidyverse)
  2. library(broom)
  3. data(iris)
  4. # Création du modèle
  5. fit <- lm(Sepal.Length ~ Petal.Length, data = iris)
  6. # Résultat
  7. fit
  8. # Résultat détaillé
  9. fit %>% summary
  10. # Test de corrélation
  11. cor.test(iris$Sepal.Length, iris$Petal.Length)
  12. # Coefficient de corrélation -> R²
  13. cor.test(iris$Sepal.Length, iris$Petal.Length)$estimate ^ 2
  14. # Utilisation de broom pour extraire les données du modèle
  15. # Glance -> paramètres du modèle
  16. fit %>% glance
  17. # Tidy -> résultats pour chaque prédicteur
  18. fit %>% tidy
  19. # Augment -> détail pour chaque observation
  20. fit %>% augment
  21. # Diagnostic du modèle
  22. fit %>% plot
  23. # Prédiction de valeurs
  24. tibble(Petal.Length = 1:7,
  25. Sepal.Length = predict(fit, tibble(Petal.Length = Petal.Length))) -> pred
  26. iris %>%
  27. ggplot() +
  28. aes(x = Petal.Length, y = Sepal.Length) +
  29. geom_point() +
  30. # geom_abline(intercept = fit %>% tidy %>% filter(term == "(Intercept)") %>% pull(estimate),
  31. # slope = fit %>% tidy %>% filter(term == "Petal.Length") %>% pull(estimate)) +
  32. geom_point(data = pred, aes(x = Petal.Length, y = Sepal.Length), color = "red")
  33. # Exemple avec gapminder
  34. library(gapminder)
  35. data(gapminder)
  36. gapminder %>%
  37. ggplot() +
  38. aes(x = year, y = lifeExp, group = country) +
  39. geom_line()
  40. gapminder %>%
  41. filter(country == "France") -> france
  42. lm(lifeExp ~ year, data = france) -> fit_fr
  43. fit_fr %>% glance
  44. fit_fr %>% tidy
  45. france %>%
  46. ggplot() +
  47. aes(x = year, y = lifeExp) +
  48. geom_line()
  49. tibble(year = 2008:2050,
  50. lifeExp = predict(fit_fr, tibble(year = year))) -> pred
  51. france %>%
  52. bind_rows(pred) %>%
  53. ggplot() +
  54. aes(x = year, y = lifeExp) +
  55. geom_line()
  56. gapminder %>%
  57. group_by(continent, country) %>%
  58. do(rsquared = lm(data = ., lifeExp ~ year) %>% glance %>% pull(r.squared)) %>%
  59. unnest -> rsq
  60. rsq %>%
  61. ggplot() +
  62. aes(x = rsquared) +
  63. geom_histogram()
  64. rsq %>%
  65. mutate(country = country %>% fct_reorder(rsquared)) %>%
  66. ggplot() +
  67. aes(x = rsquared, y = country, color = continent) +
  68. geom_point()