-
Notifications
You must be signed in to change notification settings - Fork 0
/
07-shiny.Rmd
558 lines (431 loc) · 21.8 KB
/
07-shiny.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# Appli Shiny
Cette animation montre l'évolution de l'application depuis le premier commit jusqu'au dernier.
Nous partons d'une représentation assez basique (poser les bases) vers l'ajout progressif d'éléments d'interaction utilisateur, de représentation de la données, ainsi que d'éléments contextuels textes.
Cette animation montre l'évolution de l'appli depuis le premier commit jusqu'au dernier :
![](files/shinyapp/gif/animation.gif)
Le code de l'application est accessible dans le répertoire github [shiny-artif-app](https://github.com/datagistips/shiny-artif0920-app).
## Préambule
### Template de base
Pour créer une application Shiny, il faut, depuis [RStudio](https://www.rstudio.com/products/rstudio/download/), aller dans `File > New File > Shiny Web App...`
![](files/create-shiny.png)
Cela crée une application basique qui sert d'exemple, avec une liste déroulante et un graphique d'exemple :
![](files/base-app.png)
```{r eval = FALSE }
library(shiny)
ui <- fluidPage(
## Application title
titlePanel("Old Faithful Geyser Data"), ## on changera le nom de l'appli plus tard
sidebarLayout(
sidebarPanel(
"liste"
),
mainPanel(
"résultats"
)
)
)
server <- function(input, output) {
## vide pour le moment
}
## Run the application
shinyApp(ui = ui, server = server)
```
- `ui` est la partie destinée à accueillir les éléments d'interface (esthétique)
- `server` est la partie dans laquelle seront définis les mécanismes d'interaction, d'interrogation et de représentation des données. La partie `server` réagit aux contrôles (slider, boutons, ...) définis dans `ui`
![](files/ui-server/1.jpg)
Dans l'exemple d'application de base proposée par RStudio, le plot réagit au nombre de bins (barres) défini par un slider. Ainsi, on a cette interaction :
![](files/ui-server/2.jpg)
> En quelque sorte, par analogie avec un modèle MVC (Modèle Vue Contrôleur), `ui` concerne la Vue et `server` le Contrôleur.
Dans tous les cas, on a cette modélisation pour les contrôles, sorties dans Shiny :
![](files/ui-server/3.jpg)
- un `renderStreamgraph` pourra réagir à un input de `ui`, et sera rendu dans `ui` sous la forme de `streamgraphOutput`
- un `renderText` aura son pendant `textOutput`
- etc...
Ce sont les mêmes conventions qui sont utilisées.
On a des `inputs`, des fonctions `render`, et des `outputs`
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/006bc70d801a290ef1771b69cd2ded14e0b12516) (006bc70d801a290ef1771b69cd2ded14e0b12516)
### Poser les bases
Dans un premier temps, on pose les bases, et on efface certains éléments de l'application d'exemple.
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/414c6942ce44edd411e256ab0295bb50de2fa059) (414c6942ce44edd411e256ab0295bb50de2fa059)
`server.R`
La partie est laissée vide pour le moment :
```{r eval = FALSE}
server <- function(input, output) {
## vide
}
```
### Lecture des données et liste déroulante des communes
![](files/snapshots/liste.png)
On lit les données de flux :
```{r eval = FALSE}
flux <- read_csv("data/obs_artif_conso_com_2009_2020_V2.csv", na = c("", "NULL")) %>%
filter(idreg == "93")
```
Ainsi que les données communales :
```{r eval = FALSE}
## Contours de communes
comms <<- readRDS("data/comms.rds") %>%
filter(INSEE_REG == 93)
## Liste communes
communes <- flux$idcom
names(communes) <- glue("{flux$idcomtxt} ({flux$idcom})")
```
`ui.R`
On ajoute la liste déroulante des communes maintenant qu'elles ont été lues :
```{r eval = FALSE}
sidebarLayout(
sidebarPanel(
selectInput("communes", label = NULL, choices = communes, selected = NULL),
),
mainPanel(
"Résultats"
)
)
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/9c271b706e34afff002b6e6d5df7ef895af1907e) (9c271b706e34afff002b6e6d5df7ef895af1907e)
### Affiche un tableau des résultats
![](files/snapshots/tableau.png)
On peut afficher un tableau des résultats de flux pour une commune sélectionnée, juste pour tester les mécanismes de sélection, notamment la fonction `getStatsFlux` vue dans un précédent notebook.
`ui.R`
```{r eval = FALSE}
mainPanel(
dataTableOutput("tbResults")
)
```
`server.R`
On ajoute les résultats avec `renderDataTable` et `dataTableOutput` :
```{r eval = FALSE}
output$tbResults <- renderDataTable({
codeInsee <- input$communes
df <- flux %>% getStatsFlux(codeInsee)
return(df)
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/64c7a25268157cf832c9b57dc71b7dfffd663d9e) (64c7a25268157cf832c9b57dc71b7dfffd663d9e)
## Dataviz
### Ajoute le stream
![](files/snapshots/stream.png)
On ajoute le streamgraph.
`ui.R`
```{r eval = FALSE}
mainPanel(
streamgraphOutput("streamPlot")
)
```
`server.R`
```{r eval = FALSE}
output$streamPlot <- renderStreamgraph({
myStream <- flux %>% makeStream(codeInsee)
return(myStream)
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/a402e8385afcf0c350ac0841037a69383e85eace) (a402e8385afcf0c350ac0841037a69383e85eace)
## Contexte
### Ajoute les infos communales
![](files/snapshots/texte.png)
On peut ajouter des informations assez sommaires sur la commune sélectionnée, sous la forme de texte.
`ui.R`
```{r eval = FALSE}
mainPanel(
textOutput("txtCommune"),
streamgraphOutput("streamPlot")
)
```
`server.R`
```{r eval = FALSE}
output$txtCommune <- renderText({
codeInsee <- input$communes
fComm <- flux %>% filter(idcom == codeInsee)
paste(fComm$idcomtxt, fComm$idcom, fComm$artcom0920)
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/602a3ea312be829aca7146e5563c001cdd33e823) (602a3ea312be829aca7146e5563c001cdd33e823)
### Ajoute la légende
![](files/snapshots/legende.png)
`server.R`
Pour la légende, on utilise simplement de l'HTML stylisé, plutôt que la légende du plot.
```{r eval = FALSE}
tagList(
div(
myStream,
style="margin-bottom:20px;"
),
div(
tags$span("Habitat",
style = glue("background-color:{myPalette['blue']};padding:10px;")),
tags$span("Activité",
style = glue("background-color:{myPalette['red']};padding:10px;")),
tags$span("Mixte",
style = glue("background-color:{myPalette['magenta']};padding:10px;")),
tags$span("Inconnu",
style = glue("background-color:{myPalette['grey']};padding:10px;")),
style="text-align:center"
)
)
```
On peut faire du HTML assez avancé avec R Shiny !
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/9c2ab647d7d7376fa84ee19b3239822260933d77) (9c2ab647d7d7376fa84ee19b3239822260933d77)
## Charte
### Titre avec couleurs cerema
![](files/snapshots/couleurs.png)
Ici, on intègre un élément de charte graphique Cerema, notamment la palette graphique de l'établissement au format JSON.
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/c1868418f645a374a8bfda9a3fb11bc0d72a18ec) (c1868418f645a374a8bfda9a3fb11bc0d72a18ec)
## Contexte
### Ajoute la surface artificialisée totale
On ajoute une nouvelle information en texte.
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/9c6f9bed953ea15b948fa371a1d988df5acd27ee) (9c6f9bed953ea15b948fa371a1d988df5acd27ee)
## `reactive`
### Ajout de reactive `fComm`
Les variables de type `reactive` sont très utiles lorsqu'il s'agit de récupérer à plusieurs endroits le résultat d'une variable calculée car cela évite, entre autres, de devoir répliquer les mécanismes de création de cette variable à ces multiples endroits. Aussi, un mécanisme interne permet de ne pas recalculer la variable si elle n'a pas changé avec les nouveaux critères de création.
`server.R`
```{r eval = FALSE}
fComm <- reactive({
fComm <- flux %>% filter(idcom == input$communes)
return(fComm)
})
```
On peut récupérer les variables comme ceci :
```{r eval = FALSE}
fComm()$artcom0920
fComm()$nafart0920
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/739307b7430ab0d52f3c241fd16d4404c80c927b) (739307b7430ab0d52f3c241fd16d4404c80c927b)
## Carto
### Ajoute la carte leaflet
![](files/snapshots/carte.png)
`ui.R`
```{r eval = FALSE}
leafletOutput("mymap")
```
`server.R`
```{r eval = FALSE}
output$mymap <- renderLeaflet({
leaflet() %>%
addTiles(group = "OSM")
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/5e5be7cf03e9ad4d145c292477d958af00f76904) (5e5be7cf03e9ad4d145c292477d958af00f76904)
### Centre la carte sur PACA
![](files/snapshots/paca.png)
`server.R`
Pour ajuster la carte sur PACA, on utile la fonction `fitBounds`.
```{r eval = FALSE}
output$mymap <- renderLeaflet({
bb <- st_bbox(comms) %>% as.numeric
leaflet() %>%
addTiles(group = "OSM") %>%
fitBounds(lng1 = bb[1],
lat1 = bb[2],
lng2 = bb[3],
lat2 = bb[4])
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/593b2972d14ee8f0f044fb43b2abc41932c4b1ab) (593b2972d14ee8f0f044fb43b2abc41932c4b1ab)
### Ajoute les fonds de carte
![](files/snapshots/fonds.png)
Ajoutons davantage de fonds cartos, notamment ceux de l'IGN : orthophoto, Plan IGN.
`server.R`
```{r eval = FALSE}
output$mymap <- renderLeaflet({
leaflet() %>%
addTiles(group = "OSM") %>%
addProviderTiles(providers$CartoDB.PositronOnlyLabels, group = "Villes") %>%
addTiles("http://wxs.ign.fr/choisirgeoportail/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE=normal&TILEMATRIXSET=PM&FORMAT=image/png&LAYER=GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}",
options = c(WMSTileOptions(tileSize = 256),
providerTileOptions(minZoom = 1, maxZoom = 15)),
attribution='<a target="_blank" href="https://www.geoportail.gouv.fr/">Geoportail France</a>',
group = "Plan IGN"
) %>%
addTiles("http://wxs.ign.fr/choisirgeoportail/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE=normal&TILEMATRIXSET=PM&FORMAT=image/jpeg&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}",
options = c(WMSTileOptions(tileSize = 256),
providerTileOptions(minZoom = 1, maxZoom = 22)),
attribution='<a target="_blank" href="https://www.geoportail.gouv.fr/">Geoportail France</a>',
group = "Photo aérienne"
) %>%
addLayersControl(baseGroups = c("Photo aérienne", "Plan IGN", "OSM"),
overlayGroups = "Villes",
options = layersControlOptions(collapsed = FALSE)) %>%
fitBounds(lng1 = bb[1], lat1 = bb[2], lng2 = bb[3], lat2 = bb[4])
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/fb67dcc4b87bc13a8cb81847be5c4d5aee1e2b95) (fb67dcc4b87bc13a8cb81847be5c4d5aee1e2b95)
### Coordonnées au clic
![](files/snapshots/verbatim.png)
Pour trouver les coordonnées au clic, on utile un mécanisme de sélection basé sur input, notamment input$mymap.
> A noter que l'on peut aussi réagir au clic sur une entité (`input$mymap_shape_click`), voire au passage (`input$mymap_shape_mouseover`). [Voir à ce titre la page dédiée sur R Leaflet](https://rstudio.github.io/leaflet/shiny.html#inputsevents).
`ui.R`
```{r eval = FALSE}
verbatimTextOutput("foo")
```
`server.R`
```{r eval = FALSE}
output$foo <- renderPrint({
input$mymap_click
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/a9fd41bd65be309d9a5c9e37835bad164ee9b37c) (a9fd41bd65be309d9a5c9e37835bad164ee9b37c)
## `reactive`
### Rend codeInsee reactive
Le code INSEE est récupéré dynamiquement après un clic sur la carte.
On rend le code INSEE reactive car il sera utilisé à plusieurs endroits : [ici](https://github.com/datagistips/shiny-artif-app/commit/1edc95aebfe35df74ca77370b78dc1d0402157a6#diff-ee89f65a0b4e0dccabce1672d6d689b4e2b6ca51ea1e746bdda1eca94aaa6e0fR252) ou encore [là](https://github.com/datagistips/shiny-artif-app/commit/1edc95aebfe35df74ca77370b78dc1d0402157a6#diff-ee89f65a0b4e0dccabce1672d6d689b4e2b6ca51ea1e746bdda1eca94aaa6e0fR276)
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/4ac477bd273eaf5db7b0511764c9555182ef423e) (4ac477bd273eaf5db7b0511764c9555182ef423e)
### Ajoute le reactive
On peut créer des reactive en cascade, comme ici, pour `fComm()` qui s'appuie sur `codeInsee()`
`server.R`
```{r eval = FALSE}
fComm <- reactive({
fComm <- flux %>% filter(idcom == input$communes)
fComm <- flux %>% filter(idcom == codeInsee())
return(fComm)
})
```
Pour le streamgraph, on utilise `codeInsee()` comme ceci :
```{r eval = FALSE}
myStream <- flux %>% makeStream(codeInsee())
```
► [Voir la ligne de code](https://github.com/datagistips/shiny-artif-app/commit/f3d3ffb842c07aaa67a9e4c48b922e8b4fa858dc#diff-ee89f65a0b4e0dccabce1672d6d689b4e2b6ca51ea1e746bdda1eca94aaa6e0fR174)
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/f3d3ffb842c07aaa67a9e4c48b922e8b4fa858dc) (f3d3ffb842c07aaa67a9e4c48b922e8b4fa858dc)
## Refactoring
### Fix : ajoute req
Quand les données ne sont pas encore chargées, on peut avoir un rendu bizarre avec un message d'erreur.
![](files/snapshots/error.png)
Du coup, on introduit la fonction `req` (pour 'requiert') qui exécute la suite seulement si la condition est réalisée :
```{r eval = FALSE}
fComm <- reactive({
req(codeInsee()) ## < ici
fComm <- flux %>% filter(idcom == codeInsee())
return(fComm)
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/115ac4ea9c236d74fcbfd1cb2d48d3ae6309b063) (115ac4ea9c236d74fcbfd1cb2d48d3ae6309b063)
## Carto
### Ajoute un marqueur
![](files/snapshots/marqueur.png)
On crée un proxy à la carte pour réaliser plus tard des actions sur celle-ci (zoomer, ajouter des éléments cartos) sans avoir à recalculer la carte (appelée mymap) à chaque fois :
```{r eval = FALSE}
proxy <- leafletProxy("mymap")
```
On ajoute le centroïde de la commune cliquée :
```{r eval = FALSE}
observe({
req(codeInsee())
myComm <- comms %>% filter(INSEE_COM == codeInsee())
## Ajout du marqueur
proxy %>%
clearMarkers() %>%
addMarkers(data = myComm %>% st_centroid)
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/5821ff9c63199ec0bae647a5874f2080bb9d3d5a) (5821ff9c63199ec0bae647a5874f2080bb9d3d5a)
### Ajoute le contour de la commune
![](files/snapshots/contour.png)
On ajoute le contour de la commune (c'est plus sympa) :
```{r eval = FALSE}
proxy %>%
clearShapes() %>%
addPolygons(data = myComm,
color = paletteCerema$secondaire$orange,
weight = 1,
smoothFactor = 0.5,
opacity = 1,
fillOpacity = 0.3,
fillColor = paletteCerema$secondaire$orange,
highlightOptions = highlightOptions(color = paletteCerema$secondaire$orange,
weight = 2,
fillOpacity = 0.1,
bringToFront = TRUE))
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/9b4455e5213c849edcdad0a9d2f905f377f2f84a) (9b4455e5213c849edcdad0a9d2f905f377f2f84a)
### Va vers la commune
![](files/snapshots/goto.png)
Le marqueur s'affiche, le contour aussi, mais parfois la commune semble loin, lo i n, l o i n
Du coup, petite astuce ergonomique : au clic, on va automatiquement vers la commune cliquée :
```{r eval = FALSE}
bb <- st_bbox(myComm)
proxy %>%
flyToBounds(lng1 = as.numeric(bb$xmin),
lat1 = as.numeric(bb$ymin),
lng2 = as.numeric(bb$xmax),
lat2 = as.numeric(bb$ymax))
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/404f64ab1fbd9fe00dd9da0634faf407007278b5) (404f64ab1fbd9fe00dd9da0634faf407007278b5)
### La liste déroulante permet d'aller vers une commune
![](files/snapshots/liste-goto.png)
On peut même changer le comportement de la liste déroulante utilisée au début pour afficher les stats ([voir cette ligne](https://github.com/datagistips/shiny-artif-app/commit/64c7a25268157cf832c9b57dc71b7dfffd663d9e#diff-ee89f65a0b4e0dccabce1672d6d689b4e2b6ca51ea1e746bdda1eca94aaa6e0fR73)) pour aller automatiquement vers la commune cliquée :
```{r eval = FALSE}
observeEvent(input$communes, {
codeInsee <- input$communes
bb <- comms %>% filter(INSEE_COM == codeInsee) %>% st_bbox %>% as.numeric
proxy %>% flyToBounds(lng1 = bb[1], lat1 = bb[2], lng2 = bb[3], lat2 = bb[4])
})
```
C'est aussi l'occasion d'introduire `observeEvent` qui 'écoute' les évènements, et qui, ici déclenche une action lorsqu'on choisit un élément dans la liste des communes (`input$communes`)
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/d295c184cd8801dfdcc4befb414d98ea8c0d4ea9) (d295c184cd8801dfdcc4befb414d98ea8c0d4ea9)
### Ajoute l'élément vide à la liste des communes
![](files/snapshots/empty-element.png)
Généralement, le premier élément d'une liste est une instruction type 'Veuillez choisir une commune'
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/4e5c6628148bb98841d8468d10dea8a69b2e5c6d) (4e5c6628148bb98841d8468d10dea8a69b2e5c6d)
## Refactoring
### Précise qu'il faut cliquer sur la carte pour afficher les stats
![](files/snapshots/message.png)
Au lieu d'utiliser `req` ([voir ce commit](https://github.com/datagistips/shiny-artif-app/commit/115ac4ea9c236d74fcbfd1cb2d48d3ae6309b063)) qui conditionne l'affichage à la sélection d'une commune, nous pouvons générer un message pour préciser qu'il faut cliquer sur la carte lorsqu'aucune commune n'a été cliquée.
Si aucune commune n'est sélectionnée : valeur nulle, alors on affiche ce message ([Voir la ligne de code](https://github.com/datagistips/shiny-artif-app/commit/56fd55bfa4cc066af658f7c779398c95c8276275?diff=split#diff-ee89f65a0b4e0dccabce1672d6d689b4e2b6ca51ea1e746bdda1eca94aaa6e0fR202-R203))
:
```{r eval = FALSE}
if(is.null(codeInsee())) return(tagList(icon("mouse-pointer"), "Cliquez sur la carte pour afficher les statistiques"))
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/56fd55bfa4cc066af658f7c779398c95c8276275) (56fd55bfa4cc066af658f7c779398c95c8276275)
## Dataviz
### Ajoute la treemap et supprime la légende
![](files/snapshots/treemap.png)
Tiens, comme on y est, pourquoi pas ajouter une treemap.
`ui.R`
```{r eval = FALSE}
plotlyOutput("treemap")
```
`server.R`
```{r eval = FALSE}
output$treemap <- renderPlotly({
req(codeInsee())
flux %>% makeTreemap(codeInsee())
})
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/1edc95aebfe35df74ca77370b78dc1d0402157a6) (1edc95aebfe35df74ca77370b78dc1d0402157a6)
## Refactoring
### Sépare en `ui.R`, `server.R` et `global.R`
Lorsque le code d'une application devient conséquent, cela peut être utile, plutôt que d'utiliser un unique fichier `app.R`, de séparer le contenu dans trois fichiers : `ui.R`, `server.R` et `global.R`
- `ui.R` comprend les éléments d'interface auparavant contenus dans `ui <- fluidPage({...})`
- `server.R` comprend la logique applicative et fonctionnelle de l'application : mécanismes d'interrogation et de représentation des données, auparavant contenue dans `server <- function(input, output) {...}`
- `global.R` comprend les variables utilisées dans l'application.
### Au sujet de `global.R`
Les variables contenues dans `global.R` deviennent automatiquement globales.
Il n'y a alors plus besoin d'utiliser la double flèche d'assignation des variables globales dans `global.R`
`server.R`
Précédemment, on avait ceci dans `server.R` :
```r
`monNom <<- "Mathieu"
```
### `global.R`
Dans `global.R`, la variable devient automatiquement globale même avec une assignation simple :
```r
`monNom <- "Mathieu"`
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/81991cf6ba1a4abef9df951bcdcc1858d97b6815) (81991cf6ba1a4abef9df951bcdcc1858d97b6815)
### Ajoute un fichier `helpers.R`
On peut créer un fichier annexe appelé `helpers.R` (nous aurions également pu l'appeler functions.R) dans lequel stocker les différentes stockées utilisées auparavant dans `server.R`
Cela a le mérite de rendre le code du fichier `server.R` plus _léger_, plus _lisible_ car mettant en évidence les mécanismes de façon macro plutôt que micro avec le détail de leur fonctionnement interne.
Nous faisons appel au fichier `helpers.R` au sein de `global.R`
### `global.R`
```r
source("helpers.R", encoding = "UTF-8")
```
► [Voir cette version](https://github.com/datagistips/shiny-artif-app/commit/b6a508c9db407cdc98969b50b80867554978796c) (b6a508c9db407cdc98969b50b80867554978796c)
## Contexte
On ajoute un fichier [`footer.md`](https://github.com/datagistips/shiny-artif0920-app/blob/master/footer.md) qui explique d'où vient l'application, donne les sources.
On l'intègre avec la fonction `includeMarkdown`
```{r eval = FALSE}
tags$div(
includeMarkdown("footer.md"),
style="font-size:0.8em")
```
► [Voir cette version](https://github.com/datagistips/shiny-artif0920-app/commit/d52adde3e3c68bd6e647443e5190630f75f5f9c9#diff-65704ad9823485af15425c156225c6a1aa8551dfcbb918cbb3781a4372684d62)