Projet initiale

Auteur·rice

Ilyes EL KHOMSI

1 Introduction

Pour présenter “Quarto”, nous allons nous référer à l’article de Evans (s. d.) L’auteur montre un exemple de formules mathématique en Latex. Nous avons reproduit son exemple (figure 2 de l’article) ci-dessous.

Let \(Y\sim \text{Bin}(n,p)\), where \(n\geq1\) and \(0\leq p\leq1\), then the probability mass function of \(Y\) is given by, \[ P(Y=y)=\binom{n}{p}p^y(1-p)^{n-y}, \quad y=0,1,2,\ldots, n. \] # Shiny

library(shiny)
 
# 1. Interface Utilisateur (UI)
ui <- fluidPage(
  # Ajout de MathJax pour afficher le LaTeX proprement
  withMathJax(),
  titlePanel("Visualisation Interactive : Loi Gamma"),
  sidebarLayout(
    sidebarPanel(
      helpText("Modifiez les paramètres pour voir l'impact sur la courbe."),
      # Paramètre de Forme (Alpha)
      sliderInput("alpha", "Forme (Shape) : \\(\\alpha\\)", 
                  min = 0.1, max = 10, value = 2, step = 0.1),
      # Paramètre d'Échelle (Theta)
      sliderInput("theta", "Échelle (Scale) : \\(\\theta\\)", 
                  min = 0.1, max = 5, value = 2, step = 0.1),
      hr(),
      # Rappel de la formule en bas du panneau
      helpText("Formule de la densité :"),
      uiOutput("latex_formula")
    ),
    mainPanel(
      # Zone d'affichage du graphique
      plotOutput("gammaPlot"),
      # Zone d'affichage des statistiques
      wellPanel(
        h4("Indicateurs Théoriques"),
        textOutput("esperance_text"),
        textOutput("variance_text")
      )
    )
  )
)
 
# 2. Logique Serveur
server <- function(input, output) {
  # Affichage de la formule dynamique
  output$latex_formula <- renderUI({
    withMathJax(
      paste0("$$f(x) = \\frac{x^{", input$alpha, "-1} e^{-x/", input$theta, "}}{", 
             input$theta, "^{", input$alpha, "} \\Gamma(", input$alpha, ")}$$")
    )
  })
 
  # Graphique utilisant la fonction curve()
  output$gammaPlot <- renderPlot({
    # On définit la fonction de densité avec les inputs de l'UI
    # curve() prend 'expr' comme une fonction de 'x'
    curve(dgamma(x, shape = input$alpha, scale = input$theta), 
          from = 0, to = 30, 
          n = 300, # Nombre de points pour la précision
          col = "#2c3e50", lwd = 3,
          main = paste("Densité de la Loi Gamma (", input$alpha, ",", input$theta, ")"),
          ylab = "Densité f(x)", xlab = "x",
          panel.first = grid())
    # Ajout d'une ligne verticale pour l'espérance
    esp <- input$alpha * input$theta
    abline(v = esp, col = "#e74c3c", lty = 2, lwd = 2)
    legend("topright", legend = c("Densité", "Espérance"), 
           col = c("#2c3e50", "#e74c3c"), lty = c(1, 2), lwd = 2)
  })
  # Calculs des textes de statistiques
  output$esperance_text <- renderText({
    paste("L'Espérance (moyenne théorique) est : ", input$alpha * input$theta)
  })
  output$variance_text <- renderText({
    paste("La Variance est : ", input$alpha * (input$theta^2))
  })
}
 
# Lancement de l'application
shinyApp(ui = ui, server = server)

Shiny applications not supported in static R Markdown documents

2 Tidyverse

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.0     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.2     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.1     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

2.1 Exemple préliminaire

voitures <- tibble(mtcars) #Le format de données préféré du tidyverse
64|>log()|>exp()     #Le pipe %>% ou |> dans magrittr
[1] 64
voitures%>%names()
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"
voitures$mpg
 [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4
voitures %>%
  select(mpg, cyl) %>%
  summarise(across(everything(), list(mean = mean, sd = sd))) %>%
    round(2) %>%
  pivot_longer(everything(),
               names_to = c("var", ".value"),
               names_sep = "_")
# A tibble: 2 × 3
  var    mean    sd
  <chr> <dbl> <dbl>
1 mpg   20.1   6.03
2 cyl    6.19  1.79

3 Régression linéaire et sorties Latex

library(ggthemes)
m1 <- lm(mpg~hp,voitures)

voitures%>%ggplot(aes(hp,mpg))+theme_economist()+
  ggtitle("Consommation en fonction de la puissance")+
  geom_point(col="red",size=.8)+geom_smooth(method = "lm",se=FALSE)
`geom_smooth()` using formula = 'y ~ x'

#Stargazer

library(stargazer)

Please cite as: 
 Hlavac, Marek (2022). stargazer: Well-Formatted Regression and Summary Statistics Tables.
 R package version 5.2.3. https://CRAN.R-project.org/package=stargazer 
m1

Call: lm(formula = mpg ~ hp, data = voitures)

Coefficients: (Intercept) hp
30.09886 -0.06823

stargazer(m1,type="html")
Dependent variable:
mpg
hp -0.068***
(0.010)
Constant 30.099***
(1.634)
Observations 32
R2 0.602
Adjusted R2 0.589
Residual Std. Error 3.863 (df = 30)
F Statistic 45.460*** (df = 1; 30)
Note: p<0.1; p<0.05; p<0.01

4 Travailler avec des données réelles

library(tidyverse)
library(readr)
keno_202511_6 <- read_delim("keno_202511 6.csv", 
    delim = ";", escape_double = FALSE, trim_ws = TRUE)
New names:
Rows: 100 Columns: 23
── Column specification
──────────────────────────────────────────────────────── Delimiter: ";" chr
(4): date_de_tirage, date_de_forclusion, numero_jokerplus, devise dbl (18):
annee_numero_de_tirage, boule1, boule2, boule3, boule4, boule5, bo... lgl (1):
...23
ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
Specify the column types or set `show_col_types = FALSE` to quiet this message.
• `` -> `...23`
keno_202511_6<-keno_202511_6%>%select(-c("devise","...23",1,"numero_jokerplus","multiplicateur","date_de_forclusion"))

keno_202511_6<-keno_202511_6%>%
   pivot_longer(
    cols = starts_with("boule"),
    names_to = "numero_boule",
    values_to = "valeur_boule"
  ) %>%
  mutate(numero_boule = as.numeric(gsub("boule", "", numero_boule)))

keno_202511_6 <- keno_202511_6%>%
  mutate(date_de_tirage = as.Date(date_de_tirage, format = "%d/%m/%Y"))

max(keno_202511_6$date_de_tirage) - min(keno_202511_6$date_de_tirage)
Time difference of 99 days
keno_202511_6
# A tibble: 1,600 × 3
   date_de_tirage numero_boule valeur_boule
   <date>                <dbl>        <dbl>
 1 2026-02-10                1           12
 2 2026-02-10                2           13
 3 2026-02-10                3           17
 4 2026-02-10                4           20
 5 2026-02-10                5           22
 6 2026-02-10                6           23
 7 2026-02-10                7           26
 8 2026-02-10                8           27
 9 2026-02-10                9           39
10 2026-02-10               10           42
# ℹ 1,590 more rows
library(scales)

Attaching package: 'scales'

The following object is masked from 'package:purrr':

    discard

The following object is masked from 'package:readr':

    col_factor
nb_dates <- length(unique(keno_202511_6$date_de_tirage))
freq_boules <- keno_202511_6 %>%
  count(valeur_boule, name = "nombre_sorties") %>%
  mutate(frequence = percent(nombre_sorties / nb_dates))

freq_boules
# A tibble: 56 × 3
   valeur_boule nombre_sorties frequence
          <dbl>          <int> <chr>    
 1            1             30 30.0%    
 2            2             26 26.0%    
 3            3             28 28.0%    
 4            4             32 32.0%    
 5            5             17 17.0%    
 6            6             21 21.0%    
 7            7             37 37.0%    
 8            8             23 23.0%    
 9            9             33 33.0%    
10           10             30 30.0%    
# ℹ 46 more rows

Les références

Evans, Kristian. s. d. « Innovative and interactive statistics teaching using Quarto ». Teaching Statistics n/a (n/a). https://doi.org/https://doi.org/10.1111/test.12409.