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.

310 lines
7.4KB

  1. library(tidyverse)
  2. # Un temps ----
  3. ## Data
  4. data(iris)
  5. data(mtcars)
  6. mtcars %>%
  7. mutate_at(vars(am, cyl, vs, gear), factor) ->
  8. mtcars
  9. ## Deux groupes
  10. ### Plots
  11. boxplot(mpg ~ am, data = mtcars)
  12. ggplot(mtcars) +
  13. aes(x = am, y = mpg) +
  14. geom_boxplot() +
  15. geom_point(alpha = .5)
  16. ### Paramétrique
  17. t.test(mpg ~ am, data = mtcars, var.equal = T)
  18. oneway.test(mpg ~ am, data = mtcars, var.equal = T)
  19. ### Non-paramétrique
  20. wilcox.test(mpg ~ am, data = mtcars)
  21. ## Plusieurs groupes
  22. ### Plots
  23. iris %>%
  24. ggplot() +
  25. aes(x = Species, y = Sepal.Width) +
  26. geom_violin() +
  27. geom_point(position = "jitter", alpha = .5)
  28. iris %>%
  29. ggplot() +
  30. aes(x = Petal.Length) +
  31. geom_histogram(data = iris %>% select(-Species)) +
  32. geom_histogram(aes(fill = Species)) +
  33. facet_grid(~Species)
  34. ### Paramétrique
  35. oneway.test(Sepal.Width ~ Species, data = iris)
  36. ### Non-paramétrique
  37. kruskal.test(Sepal.Width ~ Species, data = iris)
  38. ## Multivarié
  39. ### Régression linéaire
  40. # Y = a₁X₁ + a₂X₂ + _ + anXn + ε
  41. # Y = Σ aiXi + ε, ε -> N
  42. plot(mtcars)
  43. fit <- lm(mpg ~ am, data = mtcars)
  44. summary(fit)
  45. plot(fit)
  46. fit <- lm(mpg ~ cyl + disp + hp + drat + wt + vs + am, data = mtcars)
  47. summary(fit)
  48. plot(fit)
  49. ### Régression logistique
  50. fit <- glm(am ~ mpg + drat + wt, data = mtcars, family = "binomial")
  51. summary(fit)
  52. plot(fit)
  53. # Deux temps ----
  54. ## Data
  55. data(ChickWeight)
  56. ### Test apparié
  57. #### Plots
  58. ChickWeight %>%
  59. filter(Time %in% c(0, 2)) %>%
  60. ggplot() +
  61. aes(x = Time, y = weight, group = Chick, color = Diet) +
  62. geom_point() +
  63. geom_line()
  64. #### Test
  65. ChickWeight %>%
  66. group_by(Chick) %>%
  67. summarise(maxTime = max(Time)) %>%
  68. summarise(minTime = min(maxTime))
  69. t.test(ChickWeight$weight[ChickWeight$Time == 0], ChickWeight$weight[ChickWeight$Time == 2], paired = T)
  70. ### Test apparié à la main
  71. ChickWeight %>%
  72. filter(Time %in% c(0, 2)) %>%
  73. group_by(Chick) %>%
  74. summarise(weightDiff = last(weight) - first(weight),
  75. Diet = first(Diet)) -> deuxTemps
  76. #### Plots
  77. deuxTemps %>%
  78. ggplot() +
  79. aes(x = weightDiff, fill = Diet) +
  80. geom_density(alpha = .25) #, position = "fill") # position = "stack" "fill"
  81. oneway.test(weightDiff ~ Diet, data = deuxTemps)
  82. kruskal.test(weightDiff ~ Diet, data = deuxTemps)
  83. # Survie ----
  84. library(survival)
  85. ## Data
  86. data(lung)
  87. ## Bivarié
  88. lung$Surv <- Surv(lung$time, lung$status)
  89. survfit(Surv ~ 1, data = lung) -> fit
  90. plot(fit)
  91. survfit(Surv ~ sex, data = lung) -> fit
  92. plot(fit, conf.int = T, col = c("blue", "red"))
  93. legend("topright", legend = c("Hommes", "Femmes"), col = c("blue", "red"), lty = 1)
  94. survdiff(Surv ~ sex, data = lung)
  95. ## Cox
  96. coxph(Surv ~ sex + age + ph.ecog + ph.karno + meal.cal + wt.loss, data = lung) -> fit
  97. cox.zph(fit) %>% plot
  98. # N temps ----
  99. library(lme4)
  100. library(lmerTest)
  101. ## Data
  102. data(ChickWeight)
  103. ## Plots
  104. ChickWeight %>%
  105. ggplot() +
  106. aes(x = Time, y = weight, group = Chick, color = Diet) %>%
  107. geom_line()#alpha = .5) +
  108. geom_smooth(aes(x = Time, y = weight, color = Diet))
  109. ## Test
  110. lmer(weight ~ Diet + (1|Time) + (1|Chick), data = ChickWeight) -> fit
  111. summary(fit)
  112. plot(fit)
  113. # Trajectoires ----
  114. library(TraMineR)
  115. library(cluster)
  116. ## Data
  117. data(mvad)
  118. ## Description
  119. mvad.seq <- seqdef(mvad, 17:86, xtstep = 12)
  120. plot(mvad.seq, 1:20)
  121. seqdplot(mvad.seq)
  122. ## Clustering
  123. mvad.om <- seqdist(mvad.seq, method = "OM", sm = "TRATE")
  124. clusterward <- agnes(mvad.om, diss = T, method = "ward")
  125. mvad.cl <- cutree(clusterward, k = 4)
  126. cl.lab <- factor(mvad.cl, labels = paste("Cluster", 1:4))
  127. seqdplot(mvad.seq, group = cl.lab)
  128. seqfplot(mvad.seq, group = cl.lab)
  129. seqmsplot(mvad.seq, group = cl.lab)
  130. ## Analyse
  131. mvad.ent <- seqient(mvad.seq)
  132. lm.ent <- lm(mvad.ent ~ male + funemp + gcse5eq, data = mvad)
  133. summary(lm.ent)
  134. # Séries temporelles ----
  135. library(astsa)
  136. library(Rssa)
  137. library(zoo)
  138. library(TSA)
  139. ## Data
  140. data(cmort)
  141. ## Description des données
  142. is.ts(cmort) #on vérifie qu'il s'agit bien d'un objet série temporelle
  143. start(cmort) #Première observation
  144. end(cmort) #Dernière observation
  145. frequency(cmort) #Fréquance des observations
  146. deltat(cmort) #intervalle de temps entre deux observations
  147. length(cmort)
  148. head(cmort) #visualisation des premier éléments de l'objet cmort
  149. tsplot(cmort) #visualisation graphique de la série
  150. ## Méthode de décomposition
  151. MannKendall(cmort) #test de tendance : significatif donc il existe bien une tendance
  152. ### Modèle additif
  153. D_additif1 = decompose(cmort, "additive")
  154. plot(D_additif1)
  155. ### Modèle additif(autre méthode)
  156. D_additif2 = stl(cmort, "periodic")
  157. plot(D_additif2)
  158. ### Modèle multiplicatif
  159. D_multiplicatif = decompose(cmort, "multiplicative")
  160. plot(D_multiplicatif)
  161. ## Plots
  162. #Jaune : signal recomposé
  163. #Noir pointillé signal initial
  164. graph = function(var){
  165. plot(var, lwd = 2, col = "#FFC000", main = substitute(var))
  166. lines(cmort,lty = 2)
  167. }
  168. #Reconstitution signal avec décomposition additive et bruit
  169. cmort_ad1 = D_additif1$trend + D_additif1$seasonal + D_additif1$random
  170. graph(cmort_ad1)
  171. #Reconstitution signal avec décomposition additive sans bruit
  172. cmort_ad1_ssrandom = D_additif1$trend + D_additif1$seasonal
  173. graph(cmort_ad1_ssrandom)
  174. #Reconstitution signal avec décomposition additive et bruit
  175. cmort_ad2 = D_additif2$time.series[,1] + D_additif2$time.series[,2] + D_additif2$time.series[,3]
  176. graph(cmort_ad2)
  177. #Reconstitution signal avec décomposition additive sans bruit
  178. cmort_ad2_ssrandom = D_additif2$time.series[,1] + D_additif2$time.series[,2]
  179. graph(cmort_ad2_ssrandom)
  180. #Reconstitution signal avec décomposition multiplicative et bruit
  181. cmort_mult = D_multiplicatif$trend*D_multiplicatif$seasonal*D_multiplicatif$random
  182. graph(cmort_mult)
  183. #Reconstitution signal avec décomposition multiplicative sans bruit
  184. cmort_mult_ssrandom = D_multiplicatif$trend*D_multiplicatif$seasonal
  185. graph(cmort_mult_ssrandom)
  186. ### Autocorrélation et Modélisation
  187. #autocorrélation
  188. acf(cmort)
  189. #autocorrélation partielle
  190. pacf(cmort)
  191. ### Analyse spectrale
  192. #périodogramme
  193. p = periodogram(cmort)
  194. #Trouver la période :
  195. # Définir la fréquence où le spectre est maximum
  196. # Période : 1/Freq
  197. frequence = p$freq[which.max(p$spec)]
  198. Periode = 1/frequence
  199. #Lissage par moyenne mobile
  200. plot(cmort, ylab = "cmort", main = "Lissage par moyenne glissante")
  201. lines(filter(cmort, rep(1/20, 20), side = 1), col = "#FFC000", lwd = 2)
  202. lines(filter(cmort, rep(1/12, 12), side = 1), col = "red", lwd = 2)
  203. lines(filter(cmort, rep(1/50, 50), side = 1), col = "indianred4", lwd = 2)
  204. legend("topright", col = c("red", "#FFC000", "indianred4"), legend = c("1/12", "1/20", "1/100"), lwd = c(2,2,2))
  205. #Lissage par noyaux
  206. #Calcul de 3 noyaux
  207. k1 <- kernel("daniell", 10)
  208. k2 <- kernel("daniell", 5)
  209. k3 <- kernel("daniell", 30)
  210. #Application des 3 noyaux aux données
  211. x1 <- kernapply(cmort, k1)
  212. x2 <- kernapply(cmort, k2)
  213. x3 <- kernapply(cmort, k3)
  214. #Graphiques
  215. plot(cmort, main = "Lissage par noyaux")
  216. lines(x1, col = "#FFC000", lwd = 2)
  217. lines(x2, col = "red", lwd = 2)
  218. lines(x3, col = "indianred4", lwd = 2)
  219. legend("topright", col = c("red", "#FFC000", "indianred4"), legend = c("5", "10", "30"), lwd = c(2,2,2))
  220. ### Série temporelle multiple
  221. #Graphique
  222. serie = cbind(lap[,10],cmort)
  223. colnames(serie)[1] = "ozone"
  224. plot(serie)
  225. abline(v = 1970:1980, col ="#FFC000", lty = 2, lwd = 2)
  226. #Test de causalité de Granger
  227. grangertest(cmort ~ lap[,4]) #Température
  228. grangertest(cmort ~ lap[,5]) #Humidité relative
  229. grangertest(cmort ~ lap[,6]) #Monoxyde de carbone
  230. grangertest(cmort ~ lap[,7]) #Dioxyde de soufre
  231. grangertest(cmort ~ lap[,8]) #Dioxyde d'azote
  232. grangertest(cmort ~ lap[,9]) #Hydrocarbure
  233. grangertest(cmort ~ lap[,10]) #Ozone
  234. grangertest(cmort ~ lap[,11]) #Particule