R permet d’automatiser des calculs, mais aussi de générer des rapports sous différents formats qui peuvent être facilement partagés (HTML, PDF, etc). Cela se fait grâce à R Markdown (intégré dans RStudio)(cela correspond aux fichiers .Rmd).
R Markdown permet d’écrire son script R pour réaliser les actions souhaitées et d’afficher dans le même document le résultat des actions. Ainsi, il est possible d’afficher uniquement le résultat final souhaité, composé de textes, de tableaux, de graphiques, etc.
Le code Rmarkdown permettant de générer un rapport avec des visualisations de données commence par aller chercher les données qui sont dans un fichier à sélectionner (il s’agit d’un fichier contenant les réponses à un sondage de satisfaction avec les colonnes Date, Motif de visite, Note de satisfaction).
Un document Rmarkdown commence par un bloc contenant les infos du titre du document et d’eventuels parametres à prendre en compte ou à proposer à l’utilisateur (ce bloc commence et finit par ‘- – -‘).
Pour créer des parties dans le documents, il est possible de définir des titres de parties avec « ## » (par exemple : ## Mon Titre de Partie).
Les blocs executant du code R commencent et finissent par 3 backquotes (« `). Il est possible de définir dans les paramètres du bloc (via les {}) si on souhaite que le code R soit affiché ou non dans le document final qui sera généré. Pour ne pas afficher le code, on met include=FALSE. Ainsi, seul le résultat final (correspondant à ce qui serait affiché dans la console) est affiché dans le document généré. A noter que dans ces blocs où le code R est éxécuté, le caractère # correspond à des commentaires.
Pour générer des graphiques, il s’agit de faire appel à la librairie ggplot2. Pour afficher des tableaux de données, il s’agit de passer par la fonction kable de la librairie knitr (knitr::kable()).
Le code du document .Rmd génère le document HTML suivant :
Ci-dessous le code Rmarkdown permettant de générer le rapport :
2
title:
"Visualisation des reponses au sondage"
6
label:
"Ne prendre en compte que les réponses complètes:"
14
```{r setup, include=
FALSE
}
15
knitr::opts_chunk$
set
(echo =
FALSE
)
19
```{r echo =
FALSE
, warning =
FALSE
, message =
FALSE
}
36
chemin_fichier <-
choose.files
(caption=
"Selectionner le fichier de donnees"
)
37
chemin_fichier <- chemin_fichier[1]
40
data_sondage <-
read.delim
(chemin_fichier, sep =
"\t"
)
43
formatter_texte <-
function
(texte){
44
texte <- texte %>%
str_replace_all
(
"[.]"
,
"_"
) %>%
str_replace_all
(
' '
,
'_'
) %>%
str_replace_all
(
"'"
,
"_"
) %>%
str_replace_all
(
"-"
,
"_"
) %>%
str_replace_all
(
"/"
,
"_"
) %>%
str_replace_all
(
","
,
"_"
) %>%
str_replace_all
(
"[(]"
,
"_"
) %>%
str_replace_all
(
"[)]"
,
"_"
) %>%
enc2native
() %>%
iconv
(to='ASCII//TRANSLIT')
49
colnames
(data_sondage) <-
formatter_texte
(
colnames
(data_sondage))
52
if
(params$CompleteAnswersOnly ==
"OUI"
){
53
data_visualisation <- data_sondage %>%
filter
(Statut ==
"Complet"
)
55
data_visualisation <- data_sondage
59
glue
(
"Les réponses au sondage :"
)
60
knitr::
kable
(data_visualisation, align=
rep
(
'c'
, 3))
67
```{r echo =
FALSE
, warning =
FALSE
, message =
FALSE
}
73
dtMin <- data_visualisation[[
"Date"
]] %>%
as.Date
(format =
"%d/%m/%Y"
) %>%
min
() %>%
format
(format=
"%d/%m/%Y"
)
74
dtMax <- data_visualisation[[
"Date"
]] %>%
as.Date
(format =
"%d/%m/%Y"
) %>%
max
() %>%
format
(format=
"%d/%m/%Y"
)
75
glue
(
"Periode de collecte des reponses : Du {dtMin} au {dtMax}"
)
78
glue
("Rappel des parametres :
79
- Prendre en compte que les réponses complètes : {params$CompleteAnswersOnly}
87
```{r echo =
FALSE
, warning =
FALSE
, message =
FALSE
}
90
nom_question <-
"Quelle_est_votre_satisfaction"
91
nb_rep <- data_visualisation[nom_question] %>%
filter
(
is.na
(.data[[nom_question]]) ==
FALSE
& .data[[nom_question]] !=
""
) %>%
nrow
()
92
glue
(
"Nombre de repondants à la question : {nb_rep}"
)
96
visualisation_barres <-
function
(data_visualisation, nom_question, color_fill =
"#AED6F1"
, tri_asc =
TRUE
, tri_aide =
FALSE
){
98
nom_question <-
formatter_texte
(nom_question)
101
index_colonne_question <-
which
(
colnames
(data_visualisation) == nom_question)
102
reponses_possibles <- data_visualisation[nom_question] %>%
unique
()
104
data_graph <- data_visualisation[] %>%
filter
(.data[[nom_question]] !=
""
) %>%
count
(.data[[nom_question]])
105
colnames
(data_graph)[1] <-
"Reponse"
106
colnames
(data_graph)[2] <-
"Decompte"
108
total_repondants <- data_visualisation[ data_visualisation[nom_question] !=
""
,index_colonne_question] %>%
length
()
109
data_graph[,3] <- total_repondants %>%
as.numeric
()
110
colnames
(data_graph)[3] <-
'Total_repondants'
111
data_graph[,4] <- data_graph[,2] / data_graph[,3]
112
colnames
(data_graph)[4] <-
'Ratio'
114
if
( tri_asc ==
TRUE
){
115
aide_data_graph <- data_graph %>%
arrange
(
desc
(Ratio)) %>%
select
(Reponse)
116
data_graph <- data_graph %>%
mutate
(Reponse=
factor
(Reponse, levels=aide_data_graph[[
"Reponse"
]]))
117
}
else
if
(tri_asc ==
"CUSTOM"
&
is.vector
(tri_aide) ==
TRUE
){
118
data_graph <- data_graph %>%
mutate
(Reponse=
factor
(Reponse, levels=tri_aide))
123
graph_question <-
ggplot
(data=data_graph,
aes
(x=Reponse, y=Ratio)) +
124
geom_bar
(stat=
"identity"
, width = 0.5, fill = color_fill) +
128
theme
(axis.text.x =
element_text
(angle = 0, hjust = 1, vjust=1)) +
129
theme
( axis.title.x =
element_blank
(), axis.title.y =
element_blank
() ) +
130
scale_y_continuous
(labels=scales::percent)
132
return
(graph_question )
140
nom_question <-
"Quelle_est_votre_satisfaction"
141
visualisation_barres
(data_visualisation, nom_question, tri_asc=
FALSE
, color_fill=
"#A6ACAF"
) %>%
ggplotly
() %>%
config
(modeBarButtonsToRemove =
c
(
"lasso2d"
,
"pan2d"
,
"zoom2d"
))
148
visualisation_barres_avec_2eme_champ_filtre <-
function
(data_visualisation, nom_question, deuxieme_champ, color_fill =
"#AED6F1"
, tri_asc =
TRUE
, tri_aide =
FALSE
){
150
nom_question <-
formatter_texte
(nom_question)
153
index_colonne_question <-
which
(
colnames
(data_visualisation) == nom_question)
154
index_deuxieme_champ <-
which
(
colnames
(data_visualisation) == deuxieme_champ)
155
reponses_possibles <- data_visualisation[nom_question] %>%
unique
()
157
data_graph <- data_visualisation[] %>%
filter
(.data[[nom_question]] !=
""
& .data[[deuxieme_champ]] !=
""
) %>%
count
(.data[[nom_question]])
158
colnames
(data_graph)[1] <-
"Reponse"
159
colnames
(data_graph)[2] <-
"Decompte"
161
total_repondants <- data_visualisation[ data_visualisation[deuxieme_champ] !=
""
,index_deuxieme_champ] %>%
length
()
162
data_graph[,3] <- total_repondants %>%
as.numeric
()
163
colnames
(data_graph)[3] <-
'Total_repondants'
164
data_graph[,4] <- data_graph[,2] / data_graph[,3]
165
colnames
(data_graph)[4] <-
'Ratio'
167
if
( tri_asc ==
TRUE
){
168
aide_data_graph <- data_graph %>%
arrange
(Ratio) %>%
select
(Reponse) %>%
unique
()
169
data_graph <- data_graph %>%
mutate
(Reponse=
factor
(Reponse, levels=aide_data_graph[[
"Reponse"
]]))
170
}
else
if
(tri_asc ==
"CUSTOM"
&
is.vector
(tri_aide) ==
TRUE
){
171
data_graph <- data_graph %>%
mutate
(Reponse=
factor
(Reponse, levels=tri_aide))
176
graph_question <-
ggplot
(data=data_graph,
aes
(x=Reponse, y=Ratio)) +
177
geom_bar
(stat=
"identity"
, width = 0.5, fill = color_fill) +
181
theme
(axis.text.x =
element_text
(angle = 0, hjust = 1, vjust=1)) +
182
theme
( axis.title.x =
element_blank
(), axis.title.y =
element_blank
() ) +
183
scale_y_continuous
(labels=percent)
185
return
(graph_question )
189
nom_question <-
"Quel_est_votre_motif_de_visite"
190
deuxieme_champ <-
"Quelle_est_votre_satisfaction"
191
graph1 <-
visualisation_barres_avec_2eme_champ_filtre
(data_visualisation, nom_question, deuxieme_champ) %>%
ggplotly
() %>%
config
(modeBarButtonsToRemove =
c
(
"lasso2d"
,
"pan2d"
,
"zoom2d"
))
194
visualisation_barres_empiles <-
function
(data_visualisation, nom_question, champ_remplissage, libelle_axe =
TRUE
, color_fill =
c
(
"#28B463"
,
"#A9DFBF"
,
"#F9EBEA"
,
"#F1948A"
,
"#CB4335"
)){
196
nom_question <-
formatter_texte
(nom_question)
199
index_colonne_question <-
which
(
colnames
(data_visualisation) == nom_question)
200
index_champ_remplissage <-
which
(
colnames
(data_visualisation) == champ_remplissage)
201
data_graph <- data_visualisation[] %>%
filter
(.data[[nom_question]] !=
""
& .data[[champ_remplissage]] !=
""
) %>%
count
(.data[[nom_question]], .data[[champ_remplissage]])
202
colnames
(data_graph)[1] <-
"Reponse"
203
colnames
(data_graph)[2] <-
"Note"
204
colnames
(data_graph)[3] <-
"Decompte"
206
total_repondants <- data_visualisation[ data_visualisation[champ_remplissage] !=
""
,index_champ_remplissage] %>%
length
()
207
data_graph[,4] <- total_repondants %>%
as.numeric
()
208
colnames
(data_graph)[4] <-
'Total_repondants'
209
data_graph[,5] <- data_graph[,3] / data_graph[,4]
210
colnames
(data_graph)[5] <-
'Ratio'
212
aide_data_reponse <- data_graph %>%
group_by
(Reponse) %>%
summarise
(Ratio=
sum
(Ratio)) %>%
arrange
(Ratio) %>%
select
(Reponse)
213
data_graph <- data_graph %>%
mutate
(Reponses=
factor
(Reponse, levels=aide_data_reponse[[
"Reponse"
]]))
215
aide_data_note <- data_graph %>%
select
(Note) %>%
unique
() %>%
arrange
(
desc
(Note))
216
data_graph <- data_graph %>%
mutate
(Notes=
factor
(Note, levels=aide_data_note[[
"Note"
]]))
220
if
(libelle_axe ==
TRUE
){
221
graph_question <-
ggplot
(data=data_graph,
aes
(x=Reponses, y=Decompte, fill=Notes)) +
222
geom_bar
(position=
"fill"
, stat=
"identity"
) +
225
theme
(axis.text.y =
element_text
(angle = 0, hjust = 1, vjust=1), legend.position =
"top"
, legend.title=
element_blank
(), axis.title.x =
element_blank
(), axis.title.y =
element_blank
()) +
226
scale_y_continuous
(labels=percent) +
227
scale_fill_manual
(values=color_fill)
229
graph_question <-
ggplot
(data=data_graph,
aes
(x=Reponses, y=Decompte, fill=Notes)) +
230
geom_bar
(position=
"fill"
, stat=
"identity"
) +
233
theme
(axis.text.y =
element_blank
(), legend.position =
"top"
, legend.title=
element_blank
(), axis.title.x =
element_blank
(), axis.title.y =
element_blank
()) +
234
scale_y_continuous
(labels=percent) +
235
scale_fill_manual
(values=color_fill)
238
return
(graph_question)
242
reverse_legend_labels <-
function
(plotly_plot) {
243
n_labels <-
length
(plotly_plot$x$data)
244
plotly_plot$x$data[1:n_labels] <- plotly_plot$x$data[n_labels:1]
249
nom_question <-
"Quel_est_votre_motif_de_visite"
250
champ_remplissage <-
"Quelle_est_votre_satisfaction"
251
graph2 <-
visualisation_barres_empiles
(data_visualisation, nom_question, champ_remplissage, libelle_axe=
FALSE
) %>%
ggplotly
() %>%
reverse_legend_labels
() %>%
layout
(legend =
list
(orientation =
"h"
, x = 0, y = 1.2)) %>%
config
(modeBarButtonsToRemove =
c
(
"lasso2d"
,
"pan2d"
,
"zoom2d"
))
254
subplot
(graph1, graph2, widths =
c
(0.2, 0.8)) %>%
layout
(autosize =
FALSE
, width = 900)
261
glue
(
"Note moyenne par motif de visite :"
)
263
notes <- data_visualisation[[
"Quelle_est_votre_satisfaction"
]] %>%
str_sub
(1,1) %>%
as.numeric
()
265
data_tableau <- data_visualisation %>%
mutate
(notes=notes) %>%
filter
(
is.na
(notes) ==
FALSE
) %>%
group_by
(Quel_est_votre_motif_de_visite) %>%
summarise
(note_moyenne =
mean
(notes)) %>%
arrange
(
desc
(note_moyenne))
267
knitr::
kable
(data_tableau, align=
rep
(
'c'
, 3))
Et pour générer ce document HTML de manière dynamique avec du code R, il s’agit de faire appel à ce code qui génère un fichier .md à partir du fichier .Rmd (via knit), puis le fichier HTML est généré à partir du fichier .md :
4
knit
(
'monfichier.Rmd'
,
'monfichier.md'
)
5
markdownToHTML
(
'monfichier.md'
,
'monfichier.html'
)
Pour + d’infos :
https://rmarkdown.rstudio.com/lesson-1.html
https://rstudio.github.io/cheatsheets/rmarkdown.pdf
0.00 avg. rating (0 % score) - 0 votes