Programmation Statistique 2
Introduction
Davide Buscaldi
Contenus (selon le PPN)
Plan
Evaluation
Introduction à Shiny
Shiny - Exemples interactifs
Installation de Shiny
Structure d’une application Shiny
Structure d’une application Shiny
library(shiny)
# Définition UI ----
ui <- fluidPage(
...code UI
)
# Définition logique serveur ----
server <- function(input, output) {
...code serveur
}
# Exécution ----
shinyApp(ui = ui, server = server)
L’interface utilisateur
ui <- fluidPage(
titlePanel("title panel"),
sidebarLayout(
sidebarPanel("sidebar panel"),
mainPanel("main panel")
)
)
Fonctions HTML
Exemple:
h1(“Ceci est un titre de niveau 1”)
fonction Shiny | équivalent HTML | explication |
p | <p> | Paragraphe de texte |
h1 … h5 | <h1>... <h5> | Titre de niveau 1...5 |
a | <a> | Lien hypertextuel |
br | <br> | Interruption de ligne |
div | <div> | Section avec format |
span | <span> | Texte en ligne avec format |
img | <img> | Image |
strong | <strong> | Gras |
em | <em> | Italique |
HTML | | Insérer le code HTML qui suit |
Les widgets
Les Widgets
Attention ! Chaque widget a besoin d’un identifiant (inputId) et d’un libellé (label), tous deux obligatoires
Intégrer une sortie (output) à l’interface
Exemple
ui <- fluidPage(
titlePanel("censusVis"),
sidebarLayout(
sidebarPanel(
helpText("Create demographic maps with
information from the 2010 US Census."),
selectInput("var",
label = "Choose a variable to display",
choices = c("Percent White",
"Percent Black",
"Percent Hispanic",
"Percent Asian"),
selected = "Percent White"),
sliderInput("range",
label = "Range of interest:",
min = 0, max = 100, value = c(0, 100))
),
mainPanel(
textOutput("selected_var")
)
)
)
widget choix multiple nommé “var”
espace de sortie nommé “selected_var”
Le serveur
Exemple
server <- function(input, output) {
output$selected_var <- renderText({
paste("You have selected", input$var)
})
}
nom de l’espace de sortie dans l’UI
fonction de “rendering” côté serveur
valeur du contenu du widget nommé “var”
En synthèse
La réactivité : reactive()
server <- function(input, output) {
donnees <- reactive({
if (input$sexe == "Tous") t3var
else filter(t3var, sexe == input$sexe)
})
output$n <- renderText(nrow(donnees()))
output$hist <- renderPlot({
ggplot(donnees(), aes(tai)) +
geom_histogram(bins = input$bins)
})
}
Réagir à un bouton
# UI
actionButton("go", "Calculer")
# serveur
resultat <- eventReactive(input$go, {
mean(donnees()$poi)
})
output$res <- renderText(resultat())
observeEvent(input$go, {
showNotification("Calcul lancé")
})
Entrées manquantes ou invalides : req() et validate()
output$tableau <- renderTable({
req(input$fichier) # rien tant que
# pas de fichier
df <- read_csv(input$fichier$datapath)
validate(
need("tai" %in% names(df),
"Le fichier doit contenir 'tai'")
)
head(df)
})
Une interface moderne avec bslib
library(bslib)
ui <- page_sidebar(
title = "t3var",
sidebar = sidebar(
selectInput("sexe", "Sexe",
c("Tous", "h", "f")),
sliderInput("bins", "Intervalles",
5, 30, 10)
),
layout_columns(
value_box("Individus", textOutput("n")),
value_box("Taille moyenne",
textOutput("moy"))
),
card(card_header("Histogramme"),
plotOutput("hist"))
)
Tableaux et graphiques interactifs
library(DT)
library(plotly)
# UI
DTOutput("table")
plotlyOutput("nuage")
# serveur
output$table <- renderDT(donnees())
output$nuage <- renderPlotly({
p <- ggplot(donnees(),
aes(tai, poi, colour = sexe)) +
geom_point()
ggplotly(p)
})
Tester une application Shiny
library(testthat)
test_that("filtrer_sexe garde le bon sexe", {
res <- filtrer_sexe(t3var, "f")
expect_true(all(res$sexe == "f"))
})
testServer(server, {
session$setInputs(sexe = "f", bins = 10)
expect_equal(nrow(donnees()),
sum(t3var$sexe == "f"))
session$setInputs(go = 1)
expect_equal(resultat(),
mean(t3var$poi[t3var$sexe == "f"]))
})
Pour aller plus loin