-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsummary.Rmd
1463 lines (1008 loc) · 37.4 KB
/
summary.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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Premiers pas avec shiny... et les packages de visualisation interactive"
author: "B.Thieurmel, [email protected]"
output:
pdf_document:
fig_caption: no
fig_crop: no
fig_height: 2
fig_width: 3
highlight: tango
keep_tex: yes
number_sections: yes
toc: yes
toc_depth: 2
html_document:
fig_caption: no
theme: journal
toc: yes
toc_depth: 2
header-includes:
- \usepackage{graphicx}
- \usepackage{float}
---
# Shiny : créer des applications web avec le logiciel R
__Shiny__ est un package __R__ qui permet la création simple d'applications web intéractives depuis le logiciel open-source __R__.
- pas de connaissances _web_ nécessaires
- le pouvoir de calcul de R et l'intéractivité du web actuel
- pour créer des applications locales
- ou partagées avec l'utilisation de __shiny-server__, __shinyapps.io__, __shinyproxy__
<http://shiny.rstudio.com>
<http://www.shinyapps.io/>
<https://www.shinyproxy.io/>
<https://www.rstudio.com/products/shiny/shiny-server/>
Une application __shiny__ nécessite un ordinateur/un serveur éxécutant __R__

# Ma première application avec shiny
- Initialiser une application est simple avec __RStudio__, en créant un nouveau projet
* File > New Project > New Directory > Shiny Web Application
* Basée sur deux scripts : ui.R et server.R
* Et utilisant par défaut le sidebar layout
- Commandes utiles :
+ lancement de l'application : bouton __Run app__
+ actualisatisation : bouton __Reload app__
+ arrêt : bouton __Stop__

- __Run in Window__ : Nouvelle fenêtre, utilisant l'environnement __RStudio__
- __Run in Viewer Pane__ : Dans l'onglet _Viewer_ de __RStudio__
- __Run External__ : Dans le navigateur web par défaut

# Structure d'une application
## Un dossier avec un seul fichier
**conventions :**
- enregistré sous le nom __app.R__
- se terminant par la commande shinyApp()
- pour les **applications légères**

```{r, eval = FALSE}
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "num", label = "Choose a number",
value = 25, min = 1, max = 100),
plotOutput("hist")
)
server <- function(input, output) {
output$hist <- renderPlot({
hist(rnorm(input$num))
})
}
shinyApp(ui = ui, server = server)
```
## Un dossier avec deux fichiers
**conventions :**
- côté interface utilisateur dans le script __ui.R__
- côté serveur dans le script __server.R__
- structure à **priviliégier**

__ui.R__
```{r, eval = FALSE}
library(shiny)
fluidPage(
sliderInput(inputId = "num", label = "Choose a number",
value = 25, min = 1, max = 100),
plotOutput("hist")
)
```
__server.R__
```{r, eval = FALSE}
library(shiny)
function(input, output) {
output$hist <- renderPlot({hist(rnorm(input$num))})
}
```
## Données/fichiers complémentaires
- le code __R__ tourne au niveau des scripts __R__, et peut donc accéder de façon relative à tous les objets présents dans le dossier de l'application
- l'application web, comme de convention, accède à tous les éléments présents dans le dossier ``www`` (css, images, javascript, documentation, ...)

# Intéractivité et communication
## Introduction
**ui.R**:
```{r, eval = FALSE}
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Hello Shiny!"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1, max = 50, value = 30)
),
# Show a plot of the generated distribution
mainPanel(plotOutput(outputId = "distPlot"))
)
))
```
**server.R**:
```{r, eval = FALSE}
library(shiny)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
# Expression that generates a histogram. The expression is
# wrapped in a call to renderPlot to indicate that:
#
# 1) It is "reactive" and therefore should be automatically
# re-executed when inputs change
# 2) Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful[, 2] # Old Faithful Geyser data
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
})
```

Avec cette exemple simple, nous comprenons :
- Côté **ui**, nous définissons un slider numérique avec le code "`sliderInput(inputId = "bins",...)`" et on utilise sa valeur côté **server** avec la notation "`input$bins`" : c'est comme cela que le **ui** créé des variables disponibles dans le **server** !
- Côété **server**, nous créons un graphique "`output$distPlot <- renderPlot({...})`" et l'appelons dans le **ui** avec "`plotOutput(outputId = "distPlot")`", c'est comme cela que le **server** retourne des objet à **ui** !
## Process

__Le server et l'ui communiquent uniquement par le biais des inputs et des outputs__
__Par défaut, un output est mis-à-jour chaque fois qu'un input en lien change__
## Notice
__la définition de l'interface utilisateur : UI__
- la déclaration des inputs
- la structure de la page, avec le placement des outputs
__la partie serveur/calculs : SERVER__
- la déclaration et le calcul des outputs
## UI
__Deux types d'éléments dans le UI__
- xxInput(inputId = ..., ...):
* définit un élément qui permet une action de l'utilisateur
* accessible côté serveur avec son identifiant __input$inputID__

- xxOutput(ouputId = ...):
* fait référence à un output créé et défini côté serveur
* en général : graphiques et tableaux

## Serveur
__Définition des outputs dans le serveur__
- renderXX({expr}):
* calcule et retourne une sortie, dépendante d'inputs, via une expression __R__

## Retour sur le process

__C'est plus clair ?__
## Partage ui <-> server
__Le server et l'ui communiquent uniquement par le biais des inputs et des outputs__
- Nous pouvons ajouter un script nommé **global.R** pour partager des éléments (variables, packages, ...) entre la partie __UI__ et la partie __SERVER__
- Tout ce qui est présent dans le **global.R** est visible à la fois dans le __ui.R__ et dans le __server.R__
- Le script **global.R** est chargé uniquement une seul fois au lancement de l'application
- Dans le cas d'une utilisation avec un ``shiny-server``, les objets globaux sont également partagés entre les utilisateurs
# Les inputs
## Vue globale

## Valeur numérique
- La fonction
```{r, echo = TRUE, eval = FALSE}
numericInput(inputId, label, value, min = NA, max = NA, step = NA)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
numericInput(inputId = "idNumeric", label = "Please select a number",
value = 0, min = 0, max = 100, step = 10)
# For the server input$idNumeric will be of class "numeric"
# ("integer" when the parameter step is an integer value)
```

## Chaîne de caractères
- La fonction
```{r, echo = TRUE, eval = FALSE}
textInput(inputId, label, value = "")
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
textInput(inputId = "idText", label = "Enter a text", value = "")
# For the server input$idText will be of class "character"
```

## Liste de sélection
- La fonction
```{r, echo = TRUE, eval = FALSE}
selectInput(inputId, label, choices, selected = NULL, multiple = FALSE,
selectize = TRUE, width = NULL, size = NULL)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
selectInput(inputId = "idSelect", label = "Select among the list: ", selected = 3,
choices = c("First" = 1, "Second" = 2, "Third" = 3))
# For the server input$idSelect is of class "character"
# (vector when the parameter "multiple" is TRUE)
```

## Checkbox
- La fonction
```{r, echo = TRUE, eval = FALSE}
checkboxInput(inputId, label, value = FALSE)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
checkboxInput(inputId = "idCheck1", label = "Check ?")
# For the server input$idCheck1 is of class "logical"
```

## Checkboxes multiple
- La fonction
```{r, echo = TRUE, eval = FALSE}
checkboxGroupInput(inputId, label, choices, selected = NULL, inline = FALSE)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
checkboxGroupInput(inputId = "idCheckGroup", label = "Please select", selected = 3,
choices = c("First" = 1, "Second" = 2, "Third" = 3))
# For the server input$idCheckGroup is a "character" vector
```

## Radio boutons
- La fonction
```{r, echo = TRUE, eval = FALSE}
radioButtons(inputId, label, choices, selected = NULL, inline = FALSE)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
radioButtons(inputId = "idRadio", label = "Select one", selected = 3,
choices = c("First" = 1, "Second" = 2, "Third" = 3))
# For the server input$idRadio is a "character"
```

## Date
- La fonction
```{r, echo = TRUE, eval = FALSE}
dateInput(inputId, label, value = NULL, min = NULL, max = NULL, format = "yyyy-mm-dd",
startview = "month", weekstart = 0, language = "en")
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
dateInput(inputId = "idDate", label = "Please enter a date", value = "12/08/2015",
format = "dd/mm/yyyy", startview = "month", weekstart = 0, language = "fr")
# For the server input$idDate is a "Date"
```

## Période
- La fonction
```{r, echo = TRUE, eval = FALSE}
dateRangeInput(inputId, label, start = NULL, end = NULL, min = NULL, max = NULL,
format = "yyyy-mm-dd", startview = "month", weekstart = 0,
language = "en", separator = " to ")
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
dateRangeInput(inputId = "idDateRange", label = "Please Select a date range",
start = "2015-01-01", end = "2015-08-12", format = "yyyy-mm-dd",
language = "en", separator = " to ")
# For the server input$idDateRange is a vector of class "Date" with two elements
```

## Slider numérique : valeur unique
- La fonction
```{r, echo = TRUE, eval = FALSE}
sliderInput(inputId, label, min, max, value, step = NULL, round = FALSE,
format = NULL, locale = NULL, ticks = TRUE, animate = FALSE,
width = NULL, sep = ",", pre = NULL, post = NULL)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
sliderInput(inputId = "idSlider1", label = "Select a number", min = 0, max = 10,
value = 5, step = 1)
# For the server input$idSlider1 is a "numeric"
# (integer when the parameter "step" is an integer too)
```

## Slider numérique : range
- La fonction
```{r, echo = TRUE, eval = FALSE}
sliderInput(inputId, label, min, max, value, step = NULL, round = FALSE,
format = NULL, locale = NULL, ticks = TRUE, animate = FALSE,
width = NULL, sep = ",", pre = NULL, post = NULL)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
sliderInput(inputId = "idSlider2", label = "Select a number", min = 0, max = 10,
value = c(2,7), step = 1)
# For the server input$idSlider2 is a "numeric" vector
# (integer when the parameter "step" is an integer too)
```

## Importer un fichier
- La fonction
```{r, echo = TRUE, eval = FALSE}
fileInput(inputId, label, multiple = FALSE, accept = NULL)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
fileInput(inputId = "idFile", label = "Select a file")
# For the server input$idFile is a "data.frame" with four "character" columns
# (name, size, type and datapath) and one row
```

## Action Bouton
- La fonction
```{r, echo = TRUE, eval = FALSE}
actionButton(inputId, label, icon = NULL, ...)
```
- Exemple:
```{r, echo = TRUE, eval = FALSE}
actionButton(inputId = "idActionButton", label = "Click !",
icon = icon("hand-spock-o"))
# For the server input$idActionButton is an "integer"
```

## Aller plus loin : construire son propre input
__Avec un peu de compétences en HTML/CSS/JavaScript, il est également possible de construire des inputs personnalisés__
Un tutoriel est disponible : [http://shiny.rstudio.com/articles/building-inputs.html](http://shiny.rstudio.com/articles/building-inputs.html)
Ainsi que deux applications d'exemples :
- [http://shiny.rstudio.com/gallery/custom-input-control.html](http://shiny.rstudio.com/gallery/custom-input-control.html)
- [http://shiny.rstudio.com/gallery/custom-input-bindings.html](http://shiny.rstudio.com/gallery/custom-input-bindings.html)
# Outputs
## Vue globale

## Les bonnes règles de construction
- assigner l'output à afficher dans la liste __output__, avec un nom permettant l'identification côté __UI__
- utiliser une fonction __renderXX({expr})__
- __la dernière expression doit correspondre au type d'objet retourné__
- accéder aux inputs, et amener la réactivité, en utilisant la liste __input__ et l'identifiant : __input$inputId__
```{r, echo = TRUE, eval = FALSE}
#ui.R
selectInput("lettre", "Lettres:", LETTERS[1:3])
verbatimTextOutput(outputId = "selection")
#server.R
output$selection <- renderPrint({input$lettre})
```
## Print
- __ui.r__:
```{r, echo = TRUE, eval = FALSE}
verbatimTextOutput(outputId = "texte")
```
- __server.r__:
```{r, echo = TRUE, eval = FALSE}
output$texte <- renderPrint({
c("Hello shiny !")
})
```

## Text
- __ui.r__:
```{r, echo = TRUE, eval = FALSE}
textOutput(outputId = "texte")
```
- __server.r__:
```{r, echo = TRUE, eval = FALSE}
output$texte <- renderText({
c("Hello shiny !")
})
```

### Plot
- __ui.r__:
```{r, echo = TRUE, eval = FALSE}
plotOutput("myplot")
```
- __server.r__:
```{r, echo = TRUE, eval = FALSE}
output$myplot <- renderPlot({
hist(iris$Sepal.Length)
})
```

## Table
- __ui.r__:
```{r, eval=FALSE}
tableOutput(outputId = "table")
```
- __server.r__:
```{r, eval=FALSE}
output$table <- renderTable({iris})
```

## DataTable
- __ui.r__:
```{r, eval=FALSE}
dataTableOutput(outputId = "dataTable")
```
- __server.r__:
```{r, eval=FALSE}
output$dataTable <- renderDataTable({
iris
})
```

## Définir des élements de l'UI côté SERVER | Définition
__Dans certains cas, nous souhaitons définir des inputs ou des structures côté server__
Cela est possible avec les fonctions ``uiOutput`` et ``renderUI``
## Définir des élements de l'UI côté SERVER | Exemple simple
- __ui.r__:
```{r, echo = TRUE, eval = FALSE}
uiOutput(outputId = "columns")
```
- __server.r__:
```{r, echo = TRUE, eval = FALSE}
output$columns <- renderUI({
selectInput(inputId = "sel_col", label = "Column", choices = colnames(data))
})
```

## Définir des élements de l'UI côté SERVER | Exemple plus complexe
- __On peut également renvoyer un élément plus complexe de l'UI, par exemple :__
* tout en ``layout``
* ou une ``fluidRow``
- __ui.r__:
```{r, echo = TRUE, eval = FALSE}
uiOutput(outputId = "fluidRow_ui")
```
- __server.r__:
```{r, echo = TRUE, eval = FALSE}
output$fluidRow_ui <- renderUI(
fluidRow(
column(width = 3, h3("Value:")),
column(width = 3, h3(verbatimTextOutput(outputId = "slinderIn_value")))
)
)
```
## Aller plus loin : construire son propre output
__Avec un peu de compétences en HTML/CSS/JavaScript, il est également possible de construire des outputs personnalisés__
Un tutoriel est disponible : [http://shiny.rstudio.com/articles/building-outputs.html](http://shiny.rstudio.com/articles/building-outputs.html)
On peut donc par exemple ajouter comme output un graphique construit avec la librairie [d3.js](https://d3js.org/). Un exemple est disponible dans le dossier ``shinyApps/build_output``.
# Structurer sa page
## sidebarLayout
Le template basique `sidebarLayout` divise la page en deux colonnes et doit contenir :
- `sidebarPanel`, à gauche, en général pour les inputs
- `mainPanel`, à droite, en général pour les outputs
```{r , echo = TRUE, eval = FALSE}
shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"), # title
sidebarLayout(
sidebarPanel("SIDEBAR"),
mainPanel("MAINPANEL")
)
))
```

## wellPanel
Comme avec le ``sidebarPanel`` précédent, on peut griser un ensemble d'éléments en utilisant un ``wellPanel`` :
```{r , echo = TRUE, eval = FALSE}
shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"), # title
wellPanel(
sliderInput("num", "Choose a number", value = 25, min = 1, max = 100),
textInput("title", value = "Histogram", label = "Write a title")
),
plotOutput("hist")
))
```

## navbarPage
Utiliser une barre de navigation et des onglets avec `navbarPage` et `tabPanel`:
```{r , echo = TRUE, eval = FALSE}
shinyUI(
navbarPage(
title = "My first app",
tabPanel(title = "Summary",
"Here is the summary"),
tabPanel(title = "Plot",
"some charts"),
tabPanel(title = "Table",
"some tables")
)
)
```
Nous pouvons rajouter un second niveau de navigation avec un `navbarMenu` :
```{r , echo = TRUE, eval = FALSE}
shinyUI(
navbarPage(
title = "My first app",
tabPanel(title = "Summary",
"Here is the summary"),
tabPanel(title = "Plot",
"some charts"),
navbarMenu("Table",
tabPanel("Table 1"),
tabPanel("Table 2")
)
)
)
```

## tabsetPanel
Plus généralement, nous pouvons créer des onglets à n'importe quel endroit en utilisant `tabsetPanel` & `tabPanel`:
```{r , echo = TRUE, eval = FALSE}
shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"), # title
sidebarLayout(
sidebarPanel("SIDEBAR"),
mainPanel(
tabsetPanel(
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary", verbatimTextOutput("summary")),
tabPanel("Table", tableOutput("table"))
)
)
)
))
```

## navlistPanel
Une alternative au `tabsetPanel`, pour une disposition verticale plutôt qu'horizontale : ``navlistPanel``
```{r , echo = TRUE, eval = FALSE}
shinyUI(fluidPage(
navlistPanel(
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary", verbatimTextOutput("summary")),
tabPanel("Table", tableOutput("table"))
)
))
```

## Grid Layout
Créer sa propre organisation avec `fluidRow()` et `column()`
* chaque ligne peut être divisée en 12 colonnes
* le dimensionnement final de la page est automatique en fonction des éléments dans les lignes / colonnes
```{r , echo = TRUE, eval = FALSE}
tabPanel(title = "Summary",
# A fluid row can contain from 0 to 12 columns
fluidRow(
# A column is defined necessarily
# with its argument "width"
column(width = 4, "column 1"),
column(width = 4, "column 2"),
column(width = 4, "column 3"),
))
```

## shinydashboard
Le package [shinydashboard](https://rstudio.github.io/shinydashboard/) propose d'autres fonctions pour créer des tableaux de bords :

<https://rstudio.github.io/shinydashboard/>
## Combiner les structures
Toutes les structures peuvent s'utiliser en même temps !

# Graphiques intéractifs
Avec notamment l'arrivée du package [htmlwidgets](http://www.htmlwidgets.org/), de plus en plus de fonctionnalités de librairies javascript sont accessibles sous __R__ :
* [dygraphs (time series)](http://rstudio.github.io/dygraphs/)
* [DT (interactive tables)](http://rstudio.github.io/DT/)
* [Leafet (maps)](http://rstudio.github.io/leaflet/)
* [d3heatmap](https://github.com/rstudio/d3heatmap)
* [threejs (3d scatter & globe)](http://bwlewis.github.io/rthreejs)
* [rAmCharts](http://datastorm-open.github.io/introduction_ramcharts/)
* [visNetwork](http://datastorm-open.github.io/visNetwork)
* ...
Plus généralement, jeter un oeil sur la [gallerie suivante!](http://gallery.htmlwidgets.org/)
## Utilisation dans shiny
Tous ces packages sont utilisables simplement dans __shiny__. En effet, ils contiennent les deux fonctions nécessaires :
- __renderXX__
- __xxOutput__
Par exemple avec le package [dygraphs](http://rstudio.github.io/dygraphs/) :
```{r, eval = FALSE}
# Server
output$dygraph <- renderDygraph({
dygraph(predicted(), main = "Predicted Deaths/Month")
})
# Ui
dygraphOutput("dygraph")
```
Ces packages arrivent souvent avec des méthodes permettant d'intéragir avec le graphique, en créant des inputs dans **shiny** afin de déclencher des actions . Par exemple :
- __DT__ : création de *input$tableId_rows_selected*, nous informant sur la/les lignes sélectionnée(s)
- __Leaflet__ : valeurs du zoom, des clicks, de la latitude/longitude, ...
- __visNetwork__ : noeuds / groupes sélectionnés, ...
Ces points sont (en général) expliqués sur les pages web des différents packages...
De plus, il est également possible d'utiliser de nombreux événements javascripts, et de crééer des nouvelles intéractions avec **shiny** en utilisant *Shiny.onInputChange* :
```{r, eval = FALSE}
visNetwork(nodes, edges) %>%
visEvents(hoverNode = "function(nodes) {
Shiny.onInputChange('current_node_id', nodes);
;}")
```
<https://shiny.rstudio.com/articles/js-send-message.html>





# Isolation
## Définition
Par défaut, les outputs et les expressions réactives se mettent à jour automatiquement quand un des inputs présents dans le code change de valeur. Dans certains cas, on aimerait pouvoir contrôler un peu cela.
Par exemple, en utilisant un bouton de validation (__actionButton__) des inputs pour déclencher le calcul des sorties.
- un input peut être isolé comme cela `isolate(input$id)`
- une expression avec la notation suivante `isolate({expr})` et l'utilisation de ``{}``
## Exemple 1
- __ui.r__:
Trois inputs : __color__ et __bins__ pour l'histogramme, et un __actionButton__ :
```{r, echo = TRUE, eval = FALSE}
shinyUI(fluidPage(
titlePanel("Isolation"),
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "col", label = "Choose a color", inline = TRUE,
choices = c("red", "blue", "darkgrey")),
sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30),
actionButton("go_graph", "Update !")
),
mainPanel(plotOutput("distPlot"))
)
))
```
- __server.r__:
On isole tout le code sauf l'__actionButton__ :
```{r, echo = TRUE, eval = FALSE}
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
input$go_graph
isolate({
inputColor <- input$color
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = inputColor, border = 'white')
})
})
})
```
L'histogramme sera donc mis-à-jour quand l'utilisateur cliquera sur le bouton.

## Exemple 2
- __server.r__:
```{r, echo = TRUE, eval = FALSE}
output$distPlot <- renderPlot({
input$go_graph
inputColor <- input$color
isolate({
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = inputColor, border = 'white')
})
})
```
Même résultat en isolant seulement le troisième et dernier input ``input$bins``
```{r, echo = TRUE, eval = FALSE}
input$go_graph
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = isolate(input$bins) + 1)
hist(x, breaks = bins, col = input$color, border = 'white')
```
L'histogramme sera donc mis-à-jour quand l'utilisateur cliquera sur le bouton ou quand la couleur changera.
# Expressions réactives
Les expressions réactives sont très utiles quand on souhaite utiliser le même résultat/objet dans plusieurs outputs, en ne faisant le calcul qu'une fois.
Il suffit pour cela d'utiliser la fonction ``reactive`` dans le __server.R__
Par exemple, nous voulons afficher deux graphiques à la suite d'une ACP:
* La projection des individus
* La projection des variables
## Exemple sans une expression réactive
* __server.R__: le calcul est réalisé deux fois...
```{r, echo = TRUE, eval = FALSE}
require(FactoMineR) ; data("decathlon")
output$graph_pca_ind <- renderPlot({
res_pca <- PCA(decathlon[ ,input$variables], graph = FALSE)
plot.PCA(res_pca, choix = "ind", axes = c(1,2))
})
output$graph_pca_var <- renderPlot({
res_pca <- PCA(decathlon[,input$variables], graph = FALSE)
plot.PCA(res_pca, choix = "var", axes = c(1,2))
})
```