-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.html
1725 lines (1692 loc) · 150 KB
/
index.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<title>Introduction aux outils d’analyse de données et à R</title>
<script src="index_files/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="index_files/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="index_files/bootstrap-3.3.6/js/bootstrap.min.js"></script>
<script src="index_files/jqueryui-1.11.4/jquery-ui.min.js"></script>
<script src="index_files/navigation-1.1/tabsets.js"></script>
<script src="index_files/navigation-1.1/codefolding.js"></script>
<link href="index_files/magnific-popup-1.1.0/magnific-popup.css" rel="stylesheet" />
<script src="index_files/magnific-popup-1.1.0/jquery.magnific-popup.min.js"></script>
<link href="index_files/readthedown-0.1/readthedown.css" rel="stylesheet" />
<script src="index_files/readthedown-0.1/readthedown.js"></script>
!-- Matomo -->
<script type="text/javascript">
var _paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setCookieDomain", "*.datactivist.coop"]);
_paq.push(["setDomains", ["*.datactivist.coop"]]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//matomo.datactivist.coop/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '1']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<noscript><p><img src="//matomo.datactivist.coop/matomo.php?idsite=1&rec=1" style="border:0;" alt="" /></p></noscript>
<!-- End Matomo Code -->
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
a.sourceLine { display: inline-block; line-height: 1.25; }
a.sourceLine { pointer-events: none; color: inherit; text-decoration: inherit; }
a.sourceLine:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
a.sourceLine { text-indent: -1em; padding-left: 1em; }
}
pre.numberSource a.sourceLine
{ position: relative; left: -4em; }
pre.numberSource a.sourceLine::before
{ content: attr(data-line-number);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; pointer-events: all; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #ffffff;
color: #a0a0a0;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #a0a0a0; padding-left: 4px; }
div.sourceCode
{ color: #1f1c1b; background-color: #ffffff; }
@media screen {
a.sourceLine::before { text-decoration: underline; }
}
code span. { color: #1f1c1b; } /* Normal */
code span.al { color: #bf0303; background-color: #f7e6e6; font-weight: bold; } /* Alert */
code span.an { color: #ca60ca; } /* Annotation */
code span.at { color: #0057ae; } /* Attribute */
code span.bn { color: #b08000; } /* BaseN */
code span.bu { color: #644a9b; font-weight: bold; } /* BuiltIn */
code span.cf { color: #1f1c1b; font-weight: bold; } /* ControlFlow */
code span.ch { color: #924c9d; } /* Char */
code span.cn { color: #aa5500; } /* Constant */
code span.co { color: #898887; } /* Comment */
code span.cv { color: #0095ff; } /* CommentVar */
code span.do { color: #607880; } /* Documentation */
code span.dt { color: #0057ae; } /* DataType */
code span.dv { color: #b08000; } /* DecVal */
code span.er { color: #bf0303; text-decoration: underline; } /* Error */
code span.ex { color: #0095ff; font-weight: bold; } /* Extension */
code span.fl { color: #b08000; } /* Float */
code span.fu { color: #644a9b; } /* Function */
code span.im { color: #ff5500; } /* Import */
code span.in { color: #b08000; } /* Information */
code span.kw { color: #1f1c1b; font-weight: bold; } /* Keyword */
code span.op { color: #1f1c1b; } /* Operator */
code span.ot { color: #006e28; } /* Other */
code span.pp { color: #006e28; } /* Preprocessor */
code span.re { color: #0057ae; background-color: #e0e9f8; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #ff5500; } /* SpecialString */
code span.st { color: #bf0303; } /* String */
code span.va { color: #0057ae; } /* Variable */
code span.vs { color: #bf0303; } /* VerbatimString */
code span.wa { color: #bf0303; } /* Warning */
</style>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<div id="content" data-toggle="wy-nav-shift">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("text-table-of-contents");
});
</script>
<!-- code folding -->
<nav id="nav-top" role="navigation" aria-label="top navigation">
<a role="button" href="#" data-toggle="wy-nav-top"><span class="glyphicon glyphicon-menu-hamburger"></span></a>
</nav>
<div id="header">
<h1 class="title">Introduction aux outils d’analyse de données et à R</h1>
</div>
<div id="table-of-contents">
<h2><a href="#content">Introduction aux outils d’analyse de données et à R</a></h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#préambule"><span class="toc-section-number">1</span> Préambule</a></li>
<li><a href="#les-matériaux-nécessaires-pour-cette-formation"><span class="toc-section-number">2</span> Les matériaux nécessaires pour cette formation</a></li>
<li><a href="#les-étapes-de-la-formation"><span class="toc-section-number">3</span> Les étapes de la formation :</a><ul>
<li><a href="#première-démo"><span class="toc-section-number">3.1</span> Première démo :</a></li>
<li><a href="#la-donnée"><span class="toc-section-number">3.2</span> La donnée ?</a></li>
<li><a href="#quest-ce-que-lopen-data"><span class="toc-section-number">3.3</span> Qu’est ce que l’open data ?</a></li>
<li><a href="#quest-ce-que-le-big-data"><span class="toc-section-number">3.4</span> Qu’est ce que le big data ?</a></li>
<li><a href="#quest-ce-que-le-linked-data"><span class="toc-section-number">3.5</span> Qu’est ce que le linked data ?</a></li>
<li><a href="#pourquoi-sintéresser-à-lanalyse-des-données"><span class="toc-section-number">3.6</span> Pourquoi s’intéresser à l’analyse des données ?</a></li>
<li><a href="#et-vous-pourquoi-ça-vous-intéresse"><span class="toc-section-number">3.7</span> Et vous pourquoi ça vous intéresse ?</a></li>
<li><a href="#lécosystème-des-données"><span class="toc-section-number">3.8</span> L’écosystème des données</a></li>
<li><a href="#les-outils"><span class="toc-section-number">3.9</span> Les outils</a></li>
<li><a href="#les-infrastructures"><span class="toc-section-number">3.10</span> Les infrastructures</a></li>
<li><a href="#one-tool-to-rule-them-all"><span class="toc-section-number">3.11</span> One tool to rule them all</a></li>
<li><a href="#cest-quoi-tes-données"><span class="toc-section-number">3.12</span> C’est quoi tes données?</a></li>
</ul></li>
<li><a href="#installation-de-r"><span class="toc-section-number">4</span> Installation de R</a><ul>
<li><a href="#installation-du-tidyverse"><span class="toc-section-number">4.1</span> Installation du tidyverse</a></li>
<li><a href="#lancement-du-tidyverse"><span class="toc-section-number">4.2</span> Lancement du tidyverse :</a></li>
</ul></li>
<li><a href="#vocabulaire-de-r"><span class="toc-section-number">5</span> Vocabulaire de R</a></li>
<li><a href="#commandes-de-r"><span class="toc-section-number">6</span> Commandes de R</a></li>
<li><a href="#interface-de-r-studio"><span class="toc-section-number">7</span> Interface de R Studio</a></li>
<li><a href="#scripts-et-projets-sur-r"><span class="toc-section-number">8</span> Scripts et projets sur R</a><ul>
<li><a href="#créer-un-notebook"><span class="toc-section-number">8.1</span> Créer un Notebook</a></li>
<li><a href="#créer-un-r-markdown"><span class="toc-section-number">8.2</span> Créer un R Markdown</a></li>
<li><a href="#création-dun-script"><span class="toc-section-number">8.3</span> Création d’un script</a></li>
</ul></li>
<li><a href="#importer-des-données"><span class="toc-section-number">9</span> Importer des données</a><ul>
<li><a href="#sur-le-format-csv"><span class="toc-section-number">9.1</span> Sur le format CSV</a></li>
<li><a href="#avec-linterface-graphique"><span class="toc-section-number">9.2</span> Avec l’interface graphique</a></li>
<li><a href="#en-ligne-de-commandes"><span class="toc-section-number">9.3</span> En ligne de commandes</a></li>
</ul></li>
<li><a href="#afficher-les-données"><span class="toc-section-number">10</span> Afficher les données</a></li>
<li><a href="#sauvegarder-des-données"><span class="toc-section-number">11</span> Sauvegarder des données ?</a></li>
<li><a href="#nettoyer-les-données---tidy-data"><span class="toc-section-number">12</span> Nettoyer les données - tidy data</a><ul>
<li><a href="#les-principes"><span class="toc-section-number">12.1</span> Les principes</a></li>
<li><a href="#cas-pratique"><span class="toc-section-number">12.2</span> Cas pratique</a></li>
<li><a href="#préparer-des-tidy-data"><span class="toc-section-number">12.3</span> Préparer des tidy data</a></li>
<li><a href="#un-autre-exemple"><span class="toc-section-number">12.4</span> Un autre exemple</a></li>
</ul></li>
<li><a href="#pivoter-gather-et-spread-du-package-tidyr"><span class="toc-section-number">13</span> Pivoter (<code>gather</code> et <code>spread</code>, du package <code>tidyr</code>)</a><ul>
<li><a href="#cas-des-bureaux-de-votes-à-paris"><span class="toc-section-number">13.1</span> Cas des bureaux de votes à Paris</a></li>
<li><a href="#exercice-avec-des-données-électorales"><span class="toc-section-number">13.2</span> Exercice avec des données électorales</a></li>
</ul></li>
<li><a href="#quelques-autres-fonctions-utiles"><span class="toc-section-number">14</span> Quelques autres fonctions utiles</a><ul>
<li><a href="#filter-les-données"><span class="toc-section-number">14.1</span> Filter les données</a></li>
</ul></li>
<li><a href="#agréger-un-jeu-de-données-group_by-summarise"><span class="toc-section-number">15</span> Agréger un jeu de données (<code>group_by</code> + <code>summarise</code>)</a></li>
<li><a href="#fusionner-left_join"><span class="toc-section-number">16</span> Fusionner (<code>left_join</code>)</a></li>
</ul>
</div>
</div>
<div id="main">
<div id="préambule" class="section level1">
<h1><span class="header-section-number">1</span> Préambule</h1>
<p>Cette documentation est le fruit d’un travail collaboratif, réalisé par les participants à <a href="http://www.datactivi.st/formation.html">la formation organisée par Open Data France et datactivi.st</a>. Un grand merci à eux !</p>
<p>Elle accompagne les supports de formation suivants :</p>
<ul>
<li>les <a href="./jour1.html">slides de la première journée</a></li>
<li>les <a href="./jour2.html">slides de la deuxième journée</a></li>
<li>les <a href="./jour3.html">slides de la troisième journée</a></li>
<li>le <a href="https://github.com/datactivist/IntroR_ODF/blob/master/script.R">script R</a> reprenant les principales manipulations de données effectuées durant ces trois jours.</li>
</ul>
<p>La documentation correspondant au module suivant, “Utiliser R pour l’analyse et la visualisation de données”, peut être <a href="./index2.html">retrouvée ici</a>.</p>
<p>L’ensemble de ces matériaux peut être retrouvé sur le <a href="https://github.com/datactivist/IntroR_ODF">repo github dédié</a>.</p>
<p>L’ensemble de ces matériaux est placé, sauf mention contraire, sous <a href="https://creativecommons.org/licenses/by-sa/4.0/">licence Creative Commons CC-BY-SA</a>.</p>
</div>
<div id="les-matériaux-nécessaires-pour-cette-formation" class="section level1">
<h1><span class="header-section-number">2</span> Les matériaux nécessaires pour cette formation</h1>
<ul>
<li>Une bonne connexion internet pour tous</li>
<li>Un ordinateur par personne</li>
<li>Toute la documentation de la formation : www.github.com/datactivist/introR_ODF</li>
</ul>
<p>Pour le formateur :</p>
<ul>
<li>préparer les démo</li>
</ul>
</div>
<div id="les-étapes-de-la-formation" class="section level1">
<h1><span class="header-section-number">3</span> Les étapes de la formation :</h1>
<div id="première-démo" class="section level2">
<h2><span class="header-section-number">3.1</span> Première démo :</h2>
<p>Les participants renseignent le formulaire (<a href="http://frama.link/formationR" class="uri">http://frama.link/formationR</a>) qui demande des informations basiques sur les participants.
Ce formulaire sert de démonstration des usages potentiels de R.</p>
<p>Comment connecter un simple formulaire Google Form, ses données récoltées dans un tableur et les visualiser très simplement avec des petits modules de graphes ou de cartes sur une page HTML construite automatiquement.</p>
<p>Le formateur a créé préalablement <a href="https://github.com/datactivist/IntroR_ODF/blob/master/dashboard.Rmd">un code R</a> qui permet de visualiser en temps réel <a href="./dashboard.html">un dashboard</a> qui présente les résultats.</p>
<p>La force de R, c’est de permettre d’utiliser un code simple et concis (70 lignes dans ce cas). Il faut une heure à une heure et demi pour l’écrire.</p>
</div>
<div id="la-donnée" class="section level2">
<h2><span class="header-section-number">3.2</span> La donnée ?</h2>
<p>Selon vous, qu’est ce qu’une donnée ?</p>
<ul>
<li>Quantification</li>
<li>Une couleur c’est une donnée</li>
<li>Une information pas forcément lisible immédiatement, lisible par un logiciel</li>
<li>Lisible par un humain</li>
<li>Textuel ou numérique</li>
<li>Une information structurée</li>
<li>Quantification / Qualification d’un phénomène</li>
<li><p>La loi (CRPA) : donnée, lisible par machine</p></li>
<li>Définition inclusive ==/== restrictive</li>
<li><p>« Ce qui n’est pas considéré comme une donnée est une donnée »</p></li>
</ul>
<p>Comment ouvrir des données et se demander lesquelles sont à ouvrir ou pas?</p>
<p>Ile de France: Les agents doivent se justifier en cas d’un refus d’ouverture de données.</p>
<p>Avec la Loi pour une République Numérique, cette question de ce qu’est une donnée va devenir de plus en plus importante.</p>
<p>R est plus ou moins bien adapté pour traiter certains types/formats, il va falloir donc savoir à l’avance lesquelles vont représenter plus de travail ou pas à traiter avec R</p>
<blockquote>
<p><a href="https://mitpress.mit.edu/books/raw-data-oxymoron">« Raw data is an oxymoron »</a> / les données brutes sont un oxymore.</p>
</blockquote>
<p>RUSSELL ACKOFF - Théoricien des systèmes & cybernétique</p>
<p>« Il faut que l’information circule pour qu’elle ne disparaisse pas. »
Sa vision: Les données seraient brutes par essence.
Si on ouvre les données, on va créer plus de savoir et plus de sagesse.</p>
<p>Notion de données, 2 dimensions :</p>
<ul>
<li>pas de condition de véracité (Rosenberg, 2013)</li>
<li>point de départ de nouveaux réseaux sociotechniques</li>
</ul>
<p>Les données sont obtenues : « Décidément, on ne devrait jamais parler de “données”, mais toujours d’“obtenues”. » Bruno Latour, 1993</p>
<p>En statistiques, la définition de la donnée varie un peu selon le cadre conceptuel et philosophique. D’un côté, les fréquentistes, pour qui on peut tester la véracité d’énoncés au moyen d’expériences et de tests statistiques. Chaque épreuve se déroule indépendamment des croyances ou connaissances préalables. Pour les bayésiens, au contraire, il y a beaucoup plus de doutes à avoir vis-à-vis de l’objectivation du monde, c’est une approche beaucoup moins naïve qui porte sur la quantification des croyances sur le monde, qui intègre les croyances ou connaissances qu’on a déjà. Dans ce contexte, les données permettent de mettre à jour ces croyances mais n’en sont pas radicalement distinctes.</p>
</div>
<div id="quest-ce-que-lopen-data" class="section level2">
<h2><span class="header-section-number">3.3</span> Qu’est ce que l’open data ?</h2>
<p>Voir la définition de l’<a href="http://opendefinition.org/od/1.1/fr/">Open Definition</a></p>
<p>OD : données réutilisables dans des formats techniques et juridiques (2 licences : Licence Ouverte (citer la source - BY) et ODbL (citer la source + partager à l’identique : BY - SA)).</p>
<p>Les données sont généralement gratuites.</p>
<p>Réutilisation par tous, pour toutes formes d’usages.</p>
<p>Lisibles par machines.</p>
<p>Principes:</p>
<ul>
<li>Données accessibles</li>
<li>Format ouvert</li>
<li>Usage: attribuer à la source et redistribuer à l’identique</li>
</ul>
</div>
<div id="quest-ce-que-le-big-data" class="section level2">
<h2><span class="header-section-number">3.4</span> Qu’est ce que le big data ?</h2>
<p><a href="http://gph.is/29aDePB"><img src="http://i.giphy.com/TnuKaZxbMbHhK.gif" alt="What is big data anyway ?" /></a></p>
<p>Big Data : <a href="http://www.journaldunet.com/solutions/expert/51696/les-3-v-du-big-data---volume--vitesse-et-variete.shtml">règle des 3 V</a> (Vélocité, Volume, Variété) : hors des GAFA, on rencontre rarement des données massives qui respectent ces trois critères. Voir <a href="http://www.cairn.info/revue-informations-sociales-2015-5-page-26.htm">cet article de Samuel Goëta</a> qui permet de bien distinguer open data et big data.
Ces données ne sont en général pas ouvertes, c’est un trésor bien gardé des organisations.</p>
</div>
<div id="quest-ce-que-le-linked-data" class="section level2">
<h2><span class="header-section-number">3.5</span> Qu’est ce que le linked data ?</h2>
<p>Web Sémantique proposé par Tim Berners-Lee (4ème et 5ème étoiles du <a href="http://5stardata.info/en/">modèle 5* de T. Berners-Lee</a>).
Données liées, Données décrites dans des vocabulaires, des nomenclatures. Encore considéré comme une utopie, le Linked Data demeure malgré tout un objectif qualitatif intéressant</p>
<p>Un outil intéressant pour se rappeler des 5 * : <a href="http://www.cafepress.com/w3c_shop.597992118">le mug</a> !</p>
</div>
<div id="pourquoi-sintéresser-à-lanalyse-des-données" class="section level2">
<h2><span class="header-section-number">3.6</span> Pourquoi s’intéresser à l’analyse des données ?</h2>
<p>La maîtrise de l’information est un élément essentiel du rapport au pouvoir (empowerment, donnée de capacités d’action)</p>
<ul>
<li>Professionnellement</li>
<li>Personnellement, mouvement du <a href="http://mesinfos.fing.org/">self data</a> : données pour reprise en main de certaines parties de sa vie.</li>
</ul>
<p><a href="http://mesinfos.fing.org/selfdata/"><img src="img/image_domaine_usages.png" /></a></p>
<ul>
<li>Littératie de donnée</li>
<li>En tant que citoyen, déconstruire les algorithmes et se réapproprier les données qui servent à la décision publique</li>
</ul>
<p>Les données ne signifient rien à l’état brut. C’est un modèle qui permet de les interpréter : on fait des hypothèses sur le rapport des données avec la réalité et on donne du sens aux données pour confirmer/infirmer ce modèle.</p>
<div class="figure">
<img src="http://i.giphy.com/J14dxhoJLWlI4.gif" alt="fatal experience - http://gph.is/29hJuIt" />
<p class="caption">fatal experience - <a href="http://gph.is/29hJuIt" class="uri">http://gph.is/29hJuIt</a></p>
</div>
<p>Tout modèle vient avec des postulats. Il y a toujours un modèle. Quand il n’y en a pas, il est implicite.</p>
<p>Il faut donc expliciter nos modèles. Ex. de la taille : si je fais la moyenne, il faut que la distribution soit unimodale (il y a une seule valeur maximale). Si on fait la moyenne des tailles dans cette salle, c’est bimodal puisqu’il y a deux distributions différentes de la taille : les hommes et les femmes (la courbe de taille prendra la forme d’un chapeau mou avec 2 pics). La moyenne n’a aucun sens dans ce cas, ne correspond pas à une valeur interprétable. Dans ce contexte, calculer la moyenne n’a pas d’intérêt, il faut expliciter son modèle et l’adapter aux cas. La moyenne est un indicateur adapté lorsque la distribution est à peu près normale (en courbe de Gauss).</p>
<p>S’initier à l’analyse de données, c’est apprendre à expliciter ses modèles, formuler les hypothèses sous-jacentes, les tester.
Les aller-retours entre visualisations et modèle permettent de mieux préciser sa démarche.
Référence : <a href="https://fr.wikipedia.org/wiki/Edward_Tufte">Edward Tufte</a></p>
<p>In fine, il s’agit d’appréhender ses données de manière moins naïve.</p>
<p>Le workflow de l’analyse de données :</p>
<p><a href="http://r4ds.had.co.nz/explore-intro.html"><img src="img/data-science-model.png" /></a></p>
<p>En amont, import et nettoyage (phases souvent très consommatrices en temps); en aval, communication.</p>
<p>Importer -> Nettoyer -> Transformer -> Visualiser -> Modéliser -> Communiquer</p>
<p>De Transformer à Modéliser : peut être une boucle jusqu’à obtention d’un résultat satisfaisant.</p>
</div>
<div id="et-vous-pourquoi-ça-vous-intéresse" class="section level2">
<h2><span class="header-section-number">3.7</span> Et vous pourquoi ça vous intéresse ?</h2>
<p>Eléments de réponse fournis :</p>
<ul>
<li>Se doter de méthodes / outils de nettoyage et transformation</li>
<li>Mieux faire parler des données brutes, utiliser davantage nos propres données</li>
<li>Élargir la palette d’outils d’analyse de données</li>
<li>Trouver une manière de rassembler des méthodes ou outils aujourd’hui utilisés par des services différents</li>
<li>Faciliter les croisements de données</li>
<li>Coordonner transversalement des personnes qui utilisent déjà des données (BI, SIG, …)</li>
</ul>
<p>R : outil fonctionnant en ligne de commandes -> on documente ce qu’on fait, ce qui facilite la reproductibilité des différentes composantes du workflow ci-dessus (gain en efficacité).</p>
</div>
<div id="lécosystème-des-données" class="section level2">
<h2><span class="header-section-number">3.8</span> L’écosystème des données</h2>
<p>Outils déjà utilisés par les participants :</p>
<ul>
<li>Excel / Calc / tableur classique</li>
<li>SPSS, SPAD</li>
<li>Tableau</li>
<li>BO</li>
<li>Open Refine (utilisation pour du nettoyage de données ou du géocodage) : www.openrefine.org</li>
<li>CartoDB (visualisation)</li>
<li>ESRI, QGis, MapInfo (carto)</li>
</ul>
<p>Formats de données :</p>
<div class="figure">
<img src="http://i.giphy.com/jEEYJO9EgU5ig.gif" alt="Ciel mon tableur ! - http://gph.is/29aFBC1" />
<p class="caption">Ciel mon tableur ! - <a href="http://gph.is/29aFBC1" class="uri">http://gph.is/29aFBC1</a></p>
</div>
<ul>
<li>tabulaires (voir <a href="https://cran.r-project.org/web/packages/rio/vignettes/rio.html">RIO (R Input Output)</a>)</li>
<li>Excel / tableurs</li>
<li>formats texte (csv, tsv, csvy, psv, fwf) : ont l’avantage d’être publiquement documentés et relativement facilement exploitables par des machines. Moins facile à lire pour les humains</li>
<li>Datapackages : format standardisé proposé par OpenKnowledge (csv avec métadonnées en JSON pour le tabulaire), mais encore peu répandu (quelques usages significatifs sur des thématiques ciblées comme les marchés publics)</li>
<li>feather : format d’échange entre R et Python par ex. Avantage : lecture/écriture disque très rapide. Très prometteur lorsqu’il y a des échanges de gros volumes de données entre plusieurs langages</li>
<li>formats propriétaires dans le domaine des statistiques :
<ul>
<li>.dta</li>
<li>.sav, .por</li>
<li>.dbf (attention, versions incompatibles entre elles)</li>
<li>.sas7bdat, .xpt</li>
<li>…</li>
</ul></li>
<li>Formats plus exotiques :
<ul>
<li>XML</li>
<li>HTML</li>
<li>JSON (la bascule vers des données tabulaires n’est pas triviale)</li>
<li>YAML (souvent utilisé pour stocker des méta-données)</li>
<li>…</li>
</ul></li>
<li>Formats spécialisés
<ul>
<li>Exemple des données spatiales :
<ul>
<li>GDAL et sa version R (<a href="http://rgdal.sourceforge.net/">RGDAL</a> : gère 132 formats)</li>
<li>Shapefile (format propriétaire qui s’est imposé comme le standard malgré ses nombreux défauts : pas très bien documenté avec des limitations qui nuisent à l’intelligibilité)</li>
<li>GeoJSON : format ouvert, texte</li>
<li>topojson : format de données spatiales topologiques (intéressant à plusieurs points de vue)</li>
<li>kml (xml spécialisé en données spatiales)</li>
<li>mapinfo</li>
<li>formats raster (stockage plus économique que les formats vectoriels mais dégradation de la qualité lors des zooms)</li>
<li>tiles</li>
<li>…</li>
</ul></li>
</ul></li>
</ul>
<p>Bases de données :</p>
<ul>
<li>Surtout intéressantes sur de la donnée chaude (i.e. susceptible de changer souvent)</li>
<li>Bases relationnelles / SQL (orientées ligne, c’est-à-dire adaptées pour insérer, lire, mettre à jour des lignes de données) : leur performance est fortement corrélée à la manière dont les données sont indexées, ce qui est un inconvénient car il faut avoir très bien pensé son système et ses usages avant de le mettre en oeuvre
<ul>
<li>MySQL</li>
<li>SQLite (pour des volumes pas trop importants, bien adapté pour de l’électronique embarquée)</li>
<li>PostgresSQL : capacité de gestion spatiale intéressante (PostGIS) mais complexité d’administration</li>
<li>…</li>
</ul></li>
<li>Bases SQL orientées colonnes : elles sont optimisées pour lire des colonnes, adaptées pour des analyses globales sur l’ensemble du contenu d’une base
<ul>
<li>MonetDB, <a href="https://www.monetdb.org/blog/monetdblite-r">MonetDBLite</a> (utilisable dans R sans installation externe et performante, l’indexation s’effectuant à la volée)</li>
<li>…</li>
</ul></li>
<li>Bases NoSQL : bases qui ne reposent pas seulement sur une logique SQL ou tabulaire (a priori, on peut avoir différents types de données : fichiers, images, textes, etc.). Théoriquement, il n’est pas nécessaire de connaître le schéma de la table (possibilité de modifications du schéma de données en cours de route). Du coup, l’indexation est moins efficace que sur des bases SQL, ce qui amène des acteurs à mélanger des bases NoSQL et SQL pour répondre à ce souci
<ul>
<li>MongoDB</li>
<li>Cassandra</li>
<li>CouchDB</li>
<li>SimpleDB</li>
<li>BigTable</li>
<li>HBase</li>
<li>Neo4J (base orientée graphe : les enregistrements stockés sont connectés les uns aux autres)</li>
<li>Redis</li>
<li>…</li>
</ul></li>
</ul>
<p>Les API : moyen de communication entre 2 machines - <a href="https://fr.wikipedia.org/wiki/Interface_de_programmation" class="uri">https://fr.wikipedia.org/wiki/Interface_de_programmation</a></p>
<p>Beaucoup de formats de données et de types des bases de données, d’où de nombreux outils d’exploitation des données …</p>
</div>
<div id="les-outils" class="section level2">
<h2><span class="header-section-number">3.9</span> Les outils</h2>
<p>Ceux qu’on a l’habitude d’utiliser ou que tout le monde connaît :</p>
<ul>
<li>Excel, LibreOffice, un tableur quelconque
<ul>
<li>Inconvénients : se présentent comme des outils gérant des données tabulaires mais mélangent des éléments très hétérogènes, ce qui rend les données issues de ce type d’outils difficilement exploitables par des machines. Aujourd’hui, cela conduit à l’apparition <a href="http://comma-chameleon.io/">d’outils</a> qui gèrent réellement des données tabulaires avec des interfaces graphiques csv</li>
</ul></li>
</ul>
<p>Outils avec interface graphique (GUI)</p>
<ul>
<li>Sphinx</li>
<li>SPSS</li>
<li>SAS : qualité reconnue (outil préférentiel de l’INSEE jusqu’à présent; coûte très cher)</li>
<li>OpenRefine</li>
<li><a href="https://www.databasic.io/en/wtfcsv/">WTF CSV</a> : permet d’avoir une 1ère vision du contenu d’un fichier CSV sans entrer dans un outil comme R</li>
<li>Tableau : permet de faire de la belle dataviz, mais propriétaire</li>
</ul>
<p>Outils avec une interface en lignes de commande (CLI)</p>
<ul>
<li>Python</li>
<li>Julia (courbe très ascendante pour ce langage encore très jeune)</li>
<li>R</li>
<li>C/C++ (une tendance actuelle dans l’utilisation de R est d’écrire les algos les plus gourmands en C++)</li>
<li>Java</li>
<li>Javascript : langage interprété dont les utilisations se sont étendues</li>
<li>outils bash : outils qui peuvent demeurer performants mais très mals documentés et difficiles à utiliser</li>
</ul>
<p>Tous ces outils CLI s’interfacent très bien avec R.</p>
<p>Outils spécialisés. Ex: cas de la cartographie :</p>
<ul>
<li>QGis : lourd à mettre en oeuvre</li>
<li><a href="http://philcarto.free.fr/">PhilCarto</a> : permet de réaliser de la cartographie thématique. Mérite le coup d’oeil, mais mets des lunettes 80’s ;-). Propriétaire.</li>
<li>MapInfo</li>
<li>ArcGIS</li>
<li>Umap : bien adapté pour les débutants.</li>
<li>Leaflet : librairie Javascript permettant de faire de la cartographie (s’interface bien avec R)</li>
</ul>
</div>
<div id="les-infrastructures" class="section level2">
<h2><span class="header-section-number">3.10</span> Les infrastructures</h2>
<p>Celles qui se développent dans le Big Data (utilisent la parallélisation pour optimiser les traitements de données et distribuer les stockages de celles-ci) :</p>
<ul>
<li>Hadoop</li>
<li>Spark</li>
<li>H20</li>
<li>…</li>
</ul>
</div>
<div id="one-tool-to-rule-them-all" class="section level2">
<h2><span class="header-section-number">3.11</span> One tool to rule them all</h2>
<p>Un outil, R, pour aller visiter l’ensemble de ces univers.
Initialement conçu pour la manipulation des données.</p>
<p>R prend la suite de S : langage de haut niveau (= proche d’un langage compréhensible par l’homme mais relativement inefficace en terme de performances)</p>
<p>S langage développé dans les Bell Labs.
R a été développé à l’origine par des universitaires statisticiens, pour répondre à leurs besoins, sans restrictions de licences (-> caractère libre)
Le développement historique de R s’est opéré par l’intermédiaire des packages (décentralisés) développés autour du coeur du langage (qui est demeuré très stable depuis le départ).
R est devenu leader incontesté dans le domaine des statistiques avec une forte communauté internationale.
Au fil du temps, il est devenu un outil à vocation généraliste (dév. Web, machine learning, etc.). Par ailleurs, il permet d’interfacer de nombreux outils spécialisés (grâce à l’appel de librairies).</p>
<p>Énormément de ressources disponibles (souvent en anglais même si la communauté et les ressources françaises se développent). Une petite sélection :</p>
<ul>
<li>Un livre sur R : <a href="http://r4ds.had.co.nz">R for Data Science</a> de Garrett Grolemund et Hadley Wickham (rock star de R)</li>
<li>blogs : </li>
<li>des listes de diffusion thématiques</li>
<li>un site de Q/R communautaires : <a href="http://stackoverflow.com/tagged/r" class="uri">http://stackoverflow.com/tagged/r</a></li>
<li>twitter avec le hashtag #Rstats</li>
</ul>
<p>Une communauté <a href="https://rladies.org/">bienveillance avec les femmes</a>.</p>
<p>Une syntaxe de plus en plus facile</p>
<p><a href="https://rstudio.github.io/rstudioaddins/">Des progrès vers du GUI</a></p>
</div>
<div id="cest-quoi-tes-données" class="section level2">
<h2><span class="header-section-number">3.12</span> C’est quoi tes données?</h2>
<p>Les questions auxquelles il faut savoir répondre :</p>
<ul>
<li>domaine</li>
<li>format</li>
<li>taille</li>
<li>granularité</li>
<li>fraîcheur</li>
<li>quelle analyse veut-on en faire</li>
</ul>
</div>
</div>
<div id="installation-de-r" class="section level1">
<h1><span class="header-section-number">4</span> Installation de R</h1>
<ul>
<li><a href="https://cloud.r-project.org/">Installation de R</a></li>
<li>Sous windows télécharger <a href="https://cran.r-project.org/bin/windows/Rtools/">R Tools</a></li>
<li>Sous MacOS X il faut probablement <a href="https://github.com/kennethreitz/osx-gcc-installer">installer les “command line tools” ou un compilateur gcc</a> (pour pouvoir compiler des packages lorsque nécessaire)</li>
<li>Installer ensuite <a href="https://www.rstudio.com/products/rstudio/download/preview/">Rstudio</a></li>
</ul>
<div id="installation-du-tidyverse" class="section level2">
<h2><span class="header-section-number">4.1</span> Installation du tidyverse</h2>
<p>Qu’est ce que le <code>tidyverse</code> ?</p>
<ul>
<li>Le tidyverse est une suite de packages qui ont pour objet d’opérationnaliser le cycle d’analyse, depuis l’import des données jusqu’à leur représentation finale en passant par toute les étapes. Il a été développé par Hadley Wickham, connu essentiellement par son prénom dans la communauté (c’est un personnage important !). Parfois surnommé “hadleyverse” tant il est renommé, Hadley a demandé à ce qu’il soit nommé tidyverse pour valoriser la communauté et insister sur la notion de <em>tidy data</em>.<br />
</li>
<li>Liste des packages du tidyverse : broom, DBI, dplyr, forcats, ggplot2, haven, httr, hms, jsonlite, lubridate, magrittr, modelr, purrr, readr, readxl, stringr, tibble, rvest, tidyr, xml2 (<a href="https://cran.r-project.org/web/packages/tidyverse/index.html" class="uri">https://cran.r-project.org/web/packages/tidyverse/index.html</a>).</li>
<li>Pour installer le tidyverse, entrez dans la console : <code>install.packages("tidyverse")</code> puis appuyer sur entrée.
<ul>
<li>Si un warning s’affiche en précisant que le package n’est pas sous forme binaire, spécifier l’argument <code>type="source"</code> dans l’appel à la fonction <code>install.packages()</code></li>
<li>Au passage, on voit que RStudio apporte une couche d’assistance en proposant les arguments de la fonction <code>install.packages</code></li>
<li>Si le bouton “Stop” (en haut à droite de la console de Rstudio) est affiché et que le symbole « > » (invite de commande) n’est pas affiché, cela signifie que R continue de travailler.</li>
</ul></li>
<li>Quand c’est terminé on a le texte : *The downloaded binary packages are in C:_user_packages* (ou équivalent)</li>
<li>L’invite de commande est revenue : c’est ce symbole en début de ligne : « > »</li>
<li>Il est également possible d’installer des packages individuellement via Rstudio (bouton Install à droite de l’IHM). Logique de R : tout peut être fait en lignes de commande.</li>
</ul>
</div>
<div id="lancement-du-tidyverse" class="section level2">
<h2><span class="header-section-number">4.2</span> Lancement du tidyverse :</h2>
<ul>
<li>Taper library(tidyverse), R Studio propose tidyverse. Si la console affiche des conflits, ne pas en tenir compte (tidyverse informe simplement à titre préventif).</li>
</ul>
</div>
</div>
<div id="vocabulaire-de-r" class="section level1">
<h1><span class="header-section-number">5</span> Vocabulaire de R</h1>
<ul>
<li><em>Package</em> = bouts de code stockés sur le disque dur. Si on veut utiliser fonctions de ces packages, on va charger les packages : R va lire le code qui est contenu dans le package. Le code des packages est approuvé par la communauté avec des contrôles de qualité automatisés pour vérifier leur fonctionnement. De plus en plus de packages ne sont pas publiés sur CRAN (officiel) mais passent par Github où il n’y a pas le contrôle qualité (démarche entièrement “libre”).</li>
<li><em>Logiciel interprété</em> : chaque ligne de commande est exécutée séquentiellement. On envoie une ligne de commande, l’ordinateur l’interprète et l’éxécute. Après, on peut reprendre la main.</li>
<li><code>library</code> permet de charger en mémoire un package et rendre disponible les fonctions.</li>
<li><em>Environnement</em> : tous les objets que nous allons utiliser dans R.</li>
<li>L’historique reprend les différentes instructions qui ont été tapés dans le terminal.</li>
<li>Script : fichier texte ave des instructions pour R.</li>
</ul>
</div>
<div id="commandes-de-r" class="section level1">
<h1><span class="header-section-number">6</span> Commandes de R</h1>
<p>Tout ce qu’on utilise dans R : des fonctions et des données</p>
<ul>
<li><code>library</code> : chargement d’un packages</li>
<li><code>rm</code> : suppression d’un objet</li>
<li><code>glimpse</code> : pré-visualiser un jeu de données</li>
</ul>
</div>
<div id="interface-de-r-studio" class="section level1">
<h1><span class="header-section-number">7</span> Interface de R Studio</h1>
<ul>
<li>La console (généralement en bas à gauche) : fenêtre essentielle, exactement la même chose que si vous le lanciez dans un Terminal (en tapant R en ligne de commande), l’interface basique pour échanger avec un ordinateur. Le terminal permet de taper du texte et de voir la réponse de l’ordinateur.</li>
<li>Possibilité de changer les couleurs de l’interface de R Studio : aller dans onglet Options/Apparences.</li>
<li>Global Environment (en haut à droite) > contient tous les objets /fonctions que l’on va utiliser dans R</li>
<li>L’onglet “Packages” (en bas à droite) contient la liste de tous les packages installés, et permet d’en installer d’autres. On peut voir ceux qui sont chargés (cochés) et ceux qui ne le sont pas (case vide)</li>
<li>Onglet History (en haut à droite) : historique des commandes exécutées (historique recherchable, ce qui facilite la récupération d’anciennes commandes)</li>
<li>Onglet Files (en bas à droite) qui est un explorateur de fichiers de l’ordinateur. Par défaut, affiche le chemin du dossier de travail (working directory), le dossier du disque dur dans lequel R travaille.<br />
</li>
<li>Plots (en bas à droite) : Affiche les graphiques</li>
<li>L’onglet Help (en bas à droite) sert à rechercher toutes les fonctions documentées sur lesquelles on trouve un premier niveau d’aide. Documentation donne les arguments possibles de chaque package ou programmeet décrit le fonctionnement de ces arguments avec des exemples d’appels de fonctions .</li>
<li>Onglet Viewer (en vas à droite) : permet de visualiser les pages HTML et Javascript.</li>
</ul>
</div>
<div id="scripts-et-projets-sur-r" class="section level1">
<h1><span class="header-section-number">8</span> Scripts et projets sur R</h1>
<ul>
<li>Ajout d’un nouveau script : bouton en haut à droite avec la petite croix > Add a R script.
<ul>
<li>Bonne pratique : Ne jamais écrire dans la console (pour ne pas perdre l’historique de mes actions).</li>
</ul></li>
<li>Le script contient de la colaration syntaxique qui permet de mieux comprendre son code.</li>
<li>Bonne pratique : une nouvelle ligne = une nouvelle instruction</li>
<li><p>Il y a des packages de données, entrer <code>library(airlines)</code> dans le script par exemple.</p></li>
<li><p>Les scripts s’enregistrent et se sauvegardent mais contrairement à la console, il ne se passe rien directement.</p></li>
<li><p><code>library(tidyverse)</code> dans le script et appuyer sur ctrl-entrée (Windows, Linux) ou pomme-entrée (Mac). Possibilité aussi d’appuyer sur le bouton Run => exécute l’instruction (ligne par ligne).</p></li>
<li>Projet dans RStudio : crée un environnement dédié dans lequel on a les données, les scripts, l’historique.
<ul>
<li>Bonne pratique : travailler toujours dans un projet puisque c’est uniquement dans un “projet” qu’on pourra avoir un historique</li>
</ul></li>
<li>“New directory” : on définit le répertoire dans lequel les différents éléments du projet (scripts, fonctions, données) seront stockés</li>
<li>“Existing directory” : ouvrir un projet déjà existant</li>
<li>“Version control” : suivre méthodiquement en comparant les différentes versions successives des fichiers textes. L’outil le plus répandu pour ça pour Git. Plateforme la plus connue : github (mais Dropbox fait du controle de version). Controle de version n’écrase pas les versions, en cas d’accident, on peut revenir en arrière : tous les états successifs sont stockés. Les projets peuvent être collaboratifs, on peut documenter qui a fait quoi, qui a écrit telle ligne et permet de créditer les contributeurs.
<ul>
<li>Bonne pratique : soumettre son code à un versioning. Une sauvegarde s’appelle un “Commit”. On peut commenter les versions pour suivre l’évolution du projet</li>
</ul></li>
<li><p>Possibilité de créer directement à partir d’un dossier Github.
1 - Aller sur une page Github > Cliquer sur “Clone or Download” > Copie de l’URL.
2- Aller sur R, ouvrir un Nouveau projet > Controle de version et coller cette URL</p></li>
</ul>
<p>Controle de version : inclut une gestion des droits, avec un clone je ne peux pas écrire sauf si sur Github ou Gitlab le propriétaire donne des droits d’écriture.
Possibilité de pull request (proposer une modification au propriétaire du dossier Git).</p>
<ul>
<li>Créer un nouveau projet, 3 options:
<ul>
<li><pre><code>Empty > faire un nouveau projet vide</code></pre></li>
<li><pre><code>R Package > écrire un package</code></pre></li>
<li><pre><code>Shiny Web Application > une app automatique</code></pre></li>
</ul></li>
<li>On crée un nouveau projet
<ul>
<li>En haut à droite, cliquer sur new project</li>
<li>Empty project</li>
<li>Donner un nom au directory (ex. jour 2) puis indiquer où placer de dossier sur le disque dur</li>
</ul></li>
<li>Si on veut travailler sur 2 projets en parallèle:
<ul>
<li>Cliquer sur “Open in New Session”</li>
</ul></li>
</ul>
<div id="créer-un-notebook" class="section level2">
<h2><span class="header-section-number">8.1</span> Créer un Notebook</h2>
<p>️Disponible uniquement dans la preview de <a href="https://www.rstudio.com/products/rstudio/download/preview">RStudio</a> (beta mais stable)</p>
<ul>
<li>Dans le panneau de script, il est possible d’ouvrir un <a href="http://rmarkdown.rstudio.com/r_notebooks.html">notebook</a> afin de visualiser les résultats des commandes dans le script même.</li>
<li>Notebook : avoir du texte, avec du code dedans et le résultat du code (généré à la volée)</li>
<li>A priori, les notebooks ne sont pour l’instant disponibles que dans la version Preview (version beta mais stable dans la mesure où elle est rendue disponible)</li>
<li>Bien adapté pour faire une analyse interactive.</li>
<li>Différent d’un script où il n’y a que du code R</li>
</ul>
</div>
<div id="créer-un-r-markdown" class="section level2">
<h2><span class="header-section-number">8.2</span> Créer un R Markdown</h2>
<ul>
<li>Markdown: un langage, une syntaxe qui fait une mise en forme minimaliste d’un texte (gras, italique etc..)</li>
<li><a href="http://daringfireball.net/projects/markdown/syntax">Guide de la syntaxe Markdown</a></li>
<li>Très léger, simple, puissant car peut générer dess documents dans <a href="http://rmarkdown.rstudio.com/formats.html">plein de formats</a></li>
<li><p>RMarkdown : permet de prévoir la mise en page du résultat final sous la forme soit d’une page web soit d’un fichier PDF (demande l’installation de Latex sur sa machine mais pas besoin de connaitre le langage). Très pratique pour générer directement le résultat de son travail.</p></li>
<li>Pour l’installer, on peut passer par le gestionnaire de packages.️ Installer <code>rmarkdown</code> et non <code>markdown</code></li>
<li>Avec RMarkdown, je peux générer des documents, des présentations, des applications interactives avec Shiny</li>
<li><p>Il existe des templates R Markdown, soit des modules prédéfinis. Ce sont des packages à installer, de la même manière que <code>tidyverse</code> par exemple.</p></li>
</ul>
</div>
<div id="création-dun-script" class="section level2">
<h2><span class="header-section-number">8.3</span> Création d’un script</h2>
<ul>
<li>Commentaires : la ligne est préfixée par <code>#</code>
<ul>
<li>Bonne pratique : essentiel de documenter le plus explicitement possible et le plus abondamment possible</li>
<li>On peut aller jusqu’à une ligne de commentaires par ligne de code</li>
</ul></li>
<li>Il est tout à fait possible de se laisser guider par les suggestions de fonctions de Rstudio.
<ul>
<li>Exemple: si on tape “lib”, l’outil nous suggère “library” avec les arguments nécessaires. , en popup.</li>
<li>Bien regarder les valeurs par défaut dans la popup!</li>
</ul></li>
<li><p>Auto-complétion avec Tab ou Entrée</p></li>
<li>Dans <code>R</code>, 2 catégories d’êtres :
<ul>
<li>Objet: stocker “quelque chose”</li>
<li>Fonction : agissent sur des objets , à partir d’inputs produit des outputs
<ul>
<li>Chaque fonction produit une valeur (elle répond par un objet). Les inputs sont les arguments d’une fonction.</li>
<li>Parfois une fonction ne renvoit pas forcément de résultat ou de valeur, mais elle produit un effet de bord, par exemple, quand on charge un package.</li>
</ul></li>
</ul></li>
</ul>
<p>Ex. : <code>library</code>, on voit s’afficher les arguments dans une petite fenêtre qui s’affiche. Quand il y a une valeur, c’est une valeur par défaut (ils sont implicites, à moins de vouloir les modifier). Certains sont obligatoires : pour library, c’est le nom du package.</p>
<ul>
<li>2 types de problèmes possibles au cours de l’exécution du code :
<ul>
<li>Le <code>warning</code> n’arrête pas l’exécution du code.</li>
<li><code>error</code> : arrête l’exécution du code.</li>
</ul></li>
<li><p>Autant que possible, évitons de les rencontrer.</p></li>
<li><p>Donc dans <code>library</code>, on met l’argument <code>tidyverse</code>. On écrit dans le script : <code>library(tidyverse)</code>.</p></li>
<li>La console affiche des messages (c’est en rouge mais pas de problème, incohérence de R…).</li>
<li><p>On a pas besoin d’écrire <code>"tidyverse"</code> avec les guillemets. R a été fait pour des usagers sans forte compétence technique. La bonne pratique aurait été de mettre des guillemets car c’est un argument de type chaine de caractères.</p></li>
</ul>
</div>
</div>
<div id="importer-des-données" class="section level1">
<h1><span class="header-section-number">9</span> Importer des données</h1>
<div id="sur-le-format-csv" class="section level2">
<h2><span class="header-section-number">9.1</span> Sur le format CSV</h2>
<ul>
<li>CSV est venu des pratiques > différentes interprétations.</li>
<li>Il n’est pas forcément lisible par le logiciel… > nettoyage</li>
<li>Principes de base d’un fichier CSV : c’est un fichier texte</li>
<li>Les sauts de ligne sont matérialisés par des sauts de ligne (<code>\n</code>)</li>
<li>Chaque valeur est séparée par des virgules dans les pays anglo-saxons (parce qu’ils utilisent le “.” (point) pour séparer les valeurs numériques)</li>
<li><p>Le séparateur en France est le point virgule.</p></li>
<li>Bonne pratiques :
<ul>
<li>Nom des colonnes sur la 1ère ligne.</li>
<li>Mettre le texte entre guillemets –> HYPER IMPORTANT pour signifier que c’est du texte et non des valeurs numériques
<ul>
<li>Cas de la Corse : codes départements interprétés comme valeurs numériques… mais le logiciel affiche “erreur” une fois arrivé à la Corse (2A, 2B)</li>
</ul></li>
<li>Les cellules fusionnées sont à gérer comme des cellules vides, comme les commentaires</li>
<li>Voir le <a href="http://fr.slideshare.net/christophelibertidf/bonnes-pratiquesexcel-cc27juin2013">guide de Christophe Libert sur les fichiers CSV</a></li>
</ul></li>
<li>Il existe différentes propositions de standardisation (RFC 4180 est un standard CSV proposé)</li>
<li>La norme ASCII existe pour les caractères latins mais sans accents. Le RFC 4180 l’utilise</li>
<li>Norme unicode : permet d’avoir les accents. Excel l’utilise par défaut (ouas, ça dépend des OS !)</li>
<li>Libre Office gère plus facilement les fichiers avec des points virgule.</li>
<li>Passer d’un Excel à un CSV ne garantie pas une standardisation du CSV.</li>
<li>Un fichier CSV n’est pas forcément lisible par les machines</li>
<li>Mais on a des <a href="https://csvlint.io/">outils de validation du CSV</a></li>
<li>Dans les méta-données, on devrait signaler l’encodage et le caractère de séparation.</li>
<li>Peu de fichiers sont très bien expliqués (avec description des colonnes).</li>
<li><p>Tendance : faire des meta-données qui s’interprètent automatiquement (lisibles par une machine). Avoir les métadonnées permettrait d’avoir une bonne auto interprétation d’un fichier.</p></li>
</ul>
</div>
<div id="avec-linterface-graphique" class="section level2">
<h2><span class="header-section-number">9.2</span> Avec l’interface graphique</h2>
<ul>
<li>Dans le panel ‘environnement’ > Pour charger des données, il faut aller sur “import dataset” et choisir le fichier qui nous intéresse : soit sur le disque car on avait prévu l’affaire au préalable, soit en ligne en indiquant l’URL.</li>
<li>R supporte les fichiers CSV, les fichiers Excel (xls et xlsx), Stata, SPSS. Pas LibreOffice (ods).</li>
<li>Si le fichier que l’on importe a les données séparées par des ; au lieu de , il faut aller dans la boite de dialogue Delimiter et sélectionner semicolon au lieu de comma et tout de suite ça ressemble à quelque chose.</li>
<li>Attention, ️Excel pose des problèmes d’encodage avec les fichiers CSV. Ne sauvegarde pas forcément en UTF8 par défaut et n’indique pas au début du fichier comment est encodé. Quand le producteur de données a utilisé Excel pour faire son CSV, il peut y avoir des bugs. Il vaut mieux alors ouvrir le fichier dans LibreOffice et exporter en CSV (LibreOffice fait du CSV propre, lui).</li>
<li>️Beaucoup de fichiers CSV français ou francophones sont séparés par des points virgule.</li>
</ul>
</div>
<div id="en-ligne-de-commandes" class="section level2">
<h2><span class="header-section-number">9.3</span> En ligne de commandes</h2>
<div id="ouvrir-le-fichier" class="section level3">
<h3><span class="header-section-number">9.3.1</span> Ouvrir le fichier</h3>
<p>Interface graphique propose très peu de fonctions, notamment sur la localisation des fichiers. En ligne de commande, on peut tout paramétrer.</p>
<ul>
<li>Spécifier les options d’import du fichier (encodage, caractère délimiteur, …).</li>
<li>L’interface de Rstudio ne propose qu’un nb restreint d’encodage. Pour spécifier tous les types d’encodage, privilégier le script</li>
<li>Pour ouvrir un fichier CSV dans le script : <code>read_csv</code> (du package <code>readr</code>) : séparateur <code>,</code> “anglosaxon” ou <code>read_csv2</code> : séparateur <code>;</code> “francophone”</li>
</ul>
<p>Ex:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb4-1" data-line-number="1"><span class="kw">read_csv2</span>(<span class="st">"URL"</span>, <span class="dt">locale =</span> <span class="kw">locale</span>(<span class="dt">decimal_mark =</span> <span class="st">","</span>))</a></code></pre></div>
<ul>
<li>Pour la définition de l’opérateur décimal : <code>locale = locale(decimal_mark = ",")</code> ou “.” selon le fichier
<ul>
<li>Astuce : On peut s’appuyer sur l’aide de R pour trouver les arguments de <code>read_csv2</code> (rappel : aller dans help et chercher le nom de la fonction en haut à droite, c’est à dire <code>read_csv2</code>)</li>
</ul></li>
<li>Il existe une librairie - un package - simple qui s’appelle <code>rio</code> [qu’il faut télécharger: <code>install.packages("rio")</code> / <code>library(rio)</code> ] et qui simplifie certaines fonctions, comme l’import.</li>
</ul>
<div class="sourceCode" id="cb5"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb5-1" data-line-number="1">data <-<span class="st"> </span><span class="kw">import</span>(<span class="st">"nom fichier"</span>, <span class="dt">setclass =</span> <span class="st">"tbl_df"</span>)</a></code></pre></div>
<ul>
<li>Cette fonction “import” automatise la façon avec laquelle les colonnes sont parsées.</li>
</ul>
</div>
<div id="assigner-les-données" class="section level3">
<h3><span class="header-section-number">9.3.2</span> Assigner les données</h3>
<ul>
<li>Opérateur d’assignation : prend un objet et le stocke dans la mémoire. On pourra le récupérer et le travailler . Il faut indiquer <code><-</code> et le lier à la fonction de lecture des données <code>read_csv2</code>
<ul>
<li>Astuce : pour que longueur de la ligne s’adapte à la taille de la fenêtre, on va dans les préférences / code / “Soft-Wrap R Sources Files”</li>
</ul></li>
<li>On entre dans le script le nom de l’objet auquel veut assigner la valeur puis <code><-</code> puis la fonction et remplir les arguments :</li>
</ul>
<div class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb6-1" data-line-number="1">monjeudedonnees<-<span class="kw">read_csv2</span>(<span class="st">"http://www.ideeslibres.org/opendata/elus_municipaux_2008-2014/prenoms.csv"</span>)</a></code></pre></div>
<pre><code>Using ',' as decimal and '.' as grouping mark. Use read_delim() for more control.</code></pre>
<pre><code>Parsed with column specification:
cols(
prenom = col_character(),
genre = col_character(),
nb = col_double()
)</code></pre>
</div>
<div id="spécifier-les-colonnes" class="section level3">
<h3><span class="header-section-number">9.3.3</span> Spécifier les colonnes</h3>
<p>On exécute le code pour voir comment R interprète le fichier CSV. Dans la console, s’affichent les erreurs d’interprétation.
Ces erreurs vont nous aider à mieux comprendre comment spécifier son jeu de données.</p>
<p>Dans la console, on voit s’afficher un extrait des premières lignes du jeu de données et la manière dont R a interprété le type de valeurs.</p>
<ul>
<li>Il existe plusieurs types de valeurs:
<ul>
<li><code>character</code> : chaîne de caractères</li>
<li><code>integer</code> : nombre entier (important pour préserver la mémoire)</li>
<li><code>numeric</code> : entier ou décimal</li>
<li><code>double</code> : nombre décimal</li>
</ul></li>
<li>Il est important de les spécifier pour indiquer à R comment interpréter chaque colonne au mieux suivant leurs spécificités.</li>
<li><p>Quand on ne sait pas, on dit que ce sont des characters.</p></li>
<li><p>Exemple si on veut spécifier qu’une colonne est une chaîne de caractères:</p></li>
</ul>
<div class="sourceCode" id="cb9"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb9-1" data-line-number="1"> <span class="kw">read_csv2</span>(<span class="st">"monfichier.csv"</span>, </a>
<a class="sourceLine" id="cb9-2" data-line-number="2"> <span class="dt">col_types =</span> <span class="kw">cols</span> (</a>
<a class="sourceLine" id="cb9-3" data-line-number="3"> <span class="dt">colonne_nomA_avec_du_texte =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb9-4" data-line-number="4"> <span class="dt">colonne_nomB_Avec_nombres_decimaux =</span> <span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb9-5" data-line-number="5"> <span class="dt">colonne_nomC_avec_des_nombres_entiers =</span> <span class="kw">col_integer</span> ()</a>
<a class="sourceLine" id="cb9-6" data-line-number="6"> ))</a></code></pre></div>
<p>Nombre entier (<code>integer</code>) : besoin de moins d’espace pour les stocker
Nombre décimal (<code>double</code>) : prend plus d’espace pour la mémoire car plus de diversité</p>
<p>Dans le cas du jeu de données sur les prénoms, on a le code suivant :</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb10-1" data-line-number="1">monjeudedonnees <-<span class="st"> </span><span class="kw">read_csv2</span>(<span class="st">"http://www.ideeslibres.org/opendata/elus_municipaux_2008-2014/prenoms.csv"</span>, </a>
<a class="sourceLine" id="cb10-2" data-line-number="2"> <span class="dt">col_types =</span> <span class="kw">cols</span>(<span class="dt">prenom =</span> <span class="kw">col_character</span>(), </a>
<a class="sourceLine" id="cb10-3" data-line-number="3"> <span class="dt">genre =</span> <span class="kw">col_character</span>(), </a>
<a class="sourceLine" id="cb10-4" data-line-number="4"> <span class="dt">nb =</span> <span class="kw">col_integer</span>())</a>
<a class="sourceLine" id="cb10-5" data-line-number="5"> )</a></code></pre></div>
<pre><code>Using ',' as decimal and '.' as grouping mark. Use read_delim() for more control.</code></pre>
<p>Parser = prendre une suite d’éléments et les rendre interprétables. R parse le fichier automatiquement.
Il faut l’intégrer dans le script pour avoir une bonne documentation qui permettra la reproductibilité du travail.</p>
</div>
</div>
</div>
<div id="afficher-les-données" class="section level1">
<h1><span class="header-section-number">10</span> Afficher les données</h1>
<p>Une fois que le fichier est importé, on peut visualiser le résultats dans le panneau Environnement:</p>
<ul>
<li>Visualisation des données (en cliquant sur le petit tableau à droite du nom de l’objet)</li>
<li>Information sur le nombre de lignes, colonnes, taille</li>
<li>Possibilité de trier les lignes dans la visualisation</li>
<li>“Ouverture” de la table (flèche bleue) pour voir le contenu (variable, type …)</li>
<li>L’explorateur d’Environnement sert à avoir une premier preview des données</li>
</ul>
<p>Dans le script : exécuter le nom de données.
Dans notre cas, <code>monjeudedonnees</code> et le lancer.</p>
<p>Un “tibble” : un format de jeu de données qui permet notamment un affichage “propre” à l’écran :</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb12-1" data-line-number="1">monjeudedonnees</a></code></pre></div>
<pre><code># A tibble: 12,467 x 3
prenom genre nb
<chr> <chr> <int>
1 Michel M 14136
2 Alain M 10646
3 Philippe M 9903
4 Bernard M 8992
5 Christian M 8102
6 Daniel M 7821
7 Gérard M 7009
8 Jean-Pierre M 6945
9 Patrick M 6884
10 Pierre M 6711
# … with 12,457 more rows</code></pre>
<p>Pour chaque type de donnée, R sait comment l’afficher (dans la console), grâce à la méthode <code>print</code>.</p>
</div>
<div id="sauvegarder-des-données" class="section level1">
<h1><span class="header-section-number">11</span> Sauvegarder des données ?</h1>
<p>Sauvegarder permet de garder les données qui sont en mémoire .</p>
<p>À la fermeture de la session, R par défaut propose d’enregistrer les objets en mémoire. Mauvaise pratique car ne met pas à jour les données et ne permet pas de retrouver les données.</p>
<p>Fonction : <code>save(nom_du_jeu_de_données, fichier = "./nom_du_jeu_de_données.Rdata")</code></p>
<p>Le 2è argument est le chemin où on veut sauvegarder le jeu de données.</p>
<p>Les fichiers Rdata sont des binaires compressés, bcp plus léger qu’xls ou CSV. Sur des très gros fichiers, peut être utile.</p>
<p>Bonne pratique : sauvegarder un fichier par jeu de données.</p>
<p>Pratique ++ : recréer le jeu de données depuis le script.</p>
<p>Pour lire un fichier Rdata = fonction <code>load</code> (symétrique de save)
Exemple: <code>load("./nom_du_fichier.Rdata")</code></p>
<p>Avec Tab, on peut visualiser les arguments de la fonction et les fichiers disponibles dans l’arborescence.</p>
<blockquote>
<p>️Pas d’obligation de nommer les arguments… si on les enregistre dans l’ordre prévu dans l’aide ou dans la documentation en surimpression de la fonction.</p>
</blockquote>
<p>Dans l’aide, on peut savoir les arguments obligatoires : ils n’ont pas de valeurs par défaut.
Ex pour <code>load</code> :</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb14-1" data-line-number="1"><span class="kw">load</span>(file, <span class="dt">envir =</span> <span class="kw">parent.frame</span>(), <span class="dt">verbose =</span> <span class="ot">FALSE</span>) <span class="co"># file est un argument obligatoire car n'a pas de valeur par défaut</span></a></code></pre></div>
<p>Attention, ️il faut sauvegarder son script sinon on perd tout. Faire Ctrl-S (Windows, Linux ou Pomme-S) et enregistrer le script.</p>
</div>
<div id="nettoyer-les-données---tidy-data" class="section level1">
<h1><span class="header-section-number">12</span> Nettoyer les données - tidy data</h1>
<div id="les-principes" class="section level2">
<h2><span class="header-section-number">12.1</span> Les principes</h2>
<blockquote>
<p>“Happy families are all alike; every unhappy family is unhappy in its own way.” – Leo Tolstoy<em>
“Tidy datasets are all alike, but every messy dataset is messy in its own way.” – Hadley Wickham</em></p>
</blockquote>
<ul>
<li>À chaque variable sa propre colonne</li>
<li>À chaque observation sa propre ligne</li>
<li>À chaque valeur sa propre cellule > 1 jeu de données par table, dite “tibble”</li>
</ul>
</div>
<div id="cas-pratique" class="section level2">
<h2><span class="header-section-number">12.2</span> Cas pratique</h2>
<ul>
<li>Executer le code suivant :</li>
</ul>
<div class="sourceCode" id="cb15"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb15-1" data-line-number="1">P2012T1 <-<span class="st"> </span><span class="kw">read_csv2</span>(<span class="st">"https://www.dropbox.com/s/6qc3nnsiohei6f2/presidentielle2012T1.csv?raw=1"</span>, </a>
<a class="sourceLine" id="cb15-2" data-line-number="2"> <span class="dt">col_types =</span> <span class="kw">cols</span>(</a>
<a class="sourceLine" id="cb15-3" data-line-number="3"> <span class="st">`</span><span class="dt">Code du département</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-4" data-line-number="4"> <span class="st">`</span><span class="dt">Libellé du département</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-5" data-line-number="5"> <span class="st">`</span><span class="dt">Code de la commune</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-6" data-line-number="6"> <span class="st">`</span><span class="dt">Libellé de la commune</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-7" data-line-number="7"> <span class="dt">Inscrits =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-8" data-line-number="8"> <span class="dt">Abstentions =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-9" data-line-number="9"> <span class="st">`</span><span class="dt">% Abs/Ins</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-10" data-line-number="10"> <span class="dt">Votants =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-11" data-line-number="11"> <span class="st">`</span><span class="dt">% Vot/Ins</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-12" data-line-number="12"> <span class="st">`</span><span class="dt">Blancs et nuls</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-13" data-line-number="13"> <span class="st">`</span><span class="dt">% BlNuls/Ins</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-14" data-line-number="14"> <span class="st">`</span><span class="dt">% BlNuls/Vot</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-15" data-line-number="15"> Exprimé<span class="dt">s =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-16" data-line-number="16"> <span class="st">`</span><span class="dt">% Exp/Ins</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-17" data-line-number="17"> <span class="st">`</span><span class="dt">% Exp/Vot</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-18" data-line-number="18"> <span class="dt">Sexe =</span> <span class="kw">col_logical</span>(),</a>
<a class="sourceLine" id="cb15-19" data-line-number="19"> <span class="dt">Nom =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-20" data-line-number="20"> Pré<span class="dt">nom =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-21" data-line-number="21"> <span class="dt">Voix =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-22" data-line-number="22"> <span class="st">`</span><span class="dt">% Voix/Ins</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-23" data-line-number="23"> <span class="st">`</span><span class="dt">% Voix/Exp</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-24" data-line-number="24"> <span class="dt">Sexe_1 =</span> <span class="kw">col_logical</span>(),</a>
<a class="sourceLine" id="cb15-25" data-line-number="25"> <span class="dt">Nom_1 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-26" data-line-number="26"> Pré<span class="dt">nom_1 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-27" data-line-number="27"> <span class="dt">Voix_1 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-28" data-line-number="28"> <span class="st">`</span><span class="dt">% Voix/Ins_1</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-29" data-line-number="29"> <span class="st">`</span><span class="dt">% Voix/Exp_1</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-30" data-line-number="30"> <span class="dt">Sexe_2 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-31" data-line-number="31"> <span class="dt">Nom_2 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-32" data-line-number="32"> Pré<span class="dt">nom_2 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-33" data-line-number="33"> <span class="dt">Voix_2 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-34" data-line-number="34"> <span class="st">`</span><span class="dt">% Voix/Ins_2</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-35" data-line-number="35"> <span class="st">`</span><span class="dt">% Voix/Exp_2</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-36" data-line-number="36"> <span class="dt">Sexe_3 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-37" data-line-number="37"> <span class="dt">Nom_3 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-38" data-line-number="38"> Pré<span class="dt">nom_3 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-39" data-line-number="39"> <span class="dt">Voix_3 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-40" data-line-number="40"> <span class="st">`</span><span class="dt">% Voix/Ins_3</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-41" data-line-number="41"> <span class="st">`</span><span class="dt">% Voix/Exp_3</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-42" data-line-number="42"> <span class="dt">Sexe_4 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-43" data-line-number="43"> <span class="dt">Nom_4 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-44" data-line-number="44"> Pré<span class="dt">nom_4 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-45" data-line-number="45"> <span class="dt">Voix_4 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-46" data-line-number="46"> <span class="st">`</span><span class="dt">% Voix/Ins_4</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-47" data-line-number="47"> <span class="st">`</span><span class="dt">% Voix/Exp_4</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-48" data-line-number="48"> <span class="dt">Sexe_5 =</span> <span class="kw">col_logical</span>(),</a>
<a class="sourceLine" id="cb15-49" data-line-number="49"> <span class="dt">Nom_5 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-50" data-line-number="50"> Pré<span class="dt">nom_5 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-51" data-line-number="51"> <span class="dt">Voix_5 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-52" data-line-number="52"> <span class="st">`</span><span class="dt">% Voix/Ins_5</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-53" data-line-number="53"> <span class="st">`</span><span class="dt">% Voix/Exp_5</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-54" data-line-number="54"> <span class="dt">Sexe_6 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-55" data-line-number="55"> <span class="dt">Nom_6 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-56" data-line-number="56"> Pré<span class="dt">nom_6 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-57" data-line-number="57"> <span class="dt">Voix_6 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-58" data-line-number="58"> <span class="st">`</span><span class="dt">% Voix/Ins_6</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-59" data-line-number="59"> <span class="st">`</span><span class="dt">% Voix/Exp_6</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-60" data-line-number="60"> <span class="dt">Sexe_7 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-61" data-line-number="61"> <span class="dt">Nom_7 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-62" data-line-number="62"> Pré<span class="dt">nom_7 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-63" data-line-number="63"> <span class="dt">Voix_7 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-64" data-line-number="64"> <span class="st">`</span><span class="dt">% Voix/Ins_7</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-65" data-line-number="65"> <span class="st">`</span><span class="dt">% Voix/Exp_7</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-66" data-line-number="66"> <span class="dt">Sexe_8 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-67" data-line-number="67"> <span class="dt">Nom_8 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-68" data-line-number="68"> Pré<span class="dt">nom_8 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-69" data-line-number="69"> <span class="dt">Voix_8 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-70" data-line-number="70"> <span class="st">`</span><span class="dt">% Voix/Ins_8</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-71" data-line-number="71"> <span class="st">`</span><span class="dt">% Voix/Exp_8</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-72" data-line-number="72"> <span class="dt">Sexe_9 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-73" data-line-number="73"> <span class="dt">Nom_9 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-74" data-line-number="74"> Pré<span class="dt">nom_9 =</span> <span class="kw">col_character</span>(),</a>
<a class="sourceLine" id="cb15-75" data-line-number="75"> <span class="dt">Voix_9 =</span> <span class="kw">col_integer</span>(),</a>
<a class="sourceLine" id="cb15-76" data-line-number="76"> <span class="st">`</span><span class="dt">% Voix/Ins_9</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>(),</a>
<a class="sourceLine" id="cb15-77" data-line-number="77"> <span class="st">`</span><span class="dt">% Voix/Exp_9</span><span class="st">`</span> =<span class="st"> </span><span class="kw">col_double</span>())</a>
<a class="sourceLine" id="cb15-78" data-line-number="78"> )</a></code></pre></div>
<pre><code>Using ',' as decimal and '.' as grouping mark. Use read_delim() for more control.</code></pre>
<pre><code>Warning: Duplicated column names deduplicated: 'Sexe' => 'Sexe_1' [22], 'Nom'
=> 'Nom_1' [23], 'Prénom' => 'Prénom_1' [24], 'Voix' => 'Voix_1' [25], '% Voix/
Ins' => '% Voix/Ins_1' [26], '% Voix/Exp' => '% Voix/Exp_1' [27], 'Sexe' =>
'Sexe_2' [28], 'Nom' => 'Nom_2' [29], 'Prénom' => 'Prénom_2' [30], 'Voix' =>
'Voix_2' [31], '% Voix/Ins' => '% Voix/Ins_2' [32], '% Voix/Exp' => '% Voix/
Exp_2' [33], 'Sexe' => 'Sexe_3' [34], 'Nom' => 'Nom_3' [35], 'Prénom' =>
'Prénom_3' [36], 'Voix' => 'Voix_3' [37], '% Voix/Ins' => '% Voix/Ins_3' [38],
'% Voix/Exp' => '% Voix/Exp_3' [39], 'Sexe' => 'Sexe_4' [40], 'Nom' =>
'Nom_4' [41], 'Prénom' => 'Prénom_4' [42], 'Voix' => 'Voix_4' [43], '% Voix/
Ins' => '% Voix/Ins_4' [44], '% Voix/Exp' => '% Voix/Exp_4' [45], 'Sexe' =>
'Sexe_5' [46], 'Nom' => 'Nom_5' [47], 'Prénom' => 'Prénom_5' [48], 'Voix' =>
'Voix_5' [49], '% Voix/Ins' => '% Voix/Ins_5' [50], '% Voix/Exp' => '% Voix/
Exp_5' [51], 'Sexe' => 'Sexe_6' [52], 'Nom' => 'Nom_6' [53], 'Prénom' =>
'Prénom_6' [54], 'Voix' => 'Voix_6' [55], '% Voix/Ins' => '% Voix/Ins_6' [56],
'% Voix/Exp' => '% Voix/Exp_6' [57], 'Sexe' => 'Sexe_7' [58], 'Nom' =>
'Nom_7' [59], 'Prénom' => 'Prénom_7' [60], 'Voix' => 'Voix_7' [61], '% Voix/
Ins' => '% Voix/Ins_7' [62], '% Voix/Exp' => '% Voix/Exp_7' [63], 'Sexe' =>
'Sexe_8' [64], 'Nom' => 'Nom_8' [65], 'Prénom' => 'Prénom_8' [66], 'Voix' =>
'Voix_8' [67], '% Voix/Ins' => '% Voix/Ins_8' [68], '% Voix/Exp' => '% Voix/
Exp_8' [69], 'Sexe' => 'Sexe_9' [70], 'Nom' => 'Nom_9' [71], 'Prénom' =>
'Prénom_9' [72], 'Voix' => 'Voix_9' [73], '% Voix/Ins' => '% Voix/Ins_9' [74],
'% Voix/Exp' => '% Voix/Exp_9' [75]</code></pre>
<ul>
<li>R va automatiquement dédupliquer les noms des colonnes de ce jeu de données “sale”.
<ul>
<li>Info : en cas de souci d’exécution d’une fonction, il est conseillé de sélectionner la totalité de l’appel à la fonction et de faire un CTRL + Entrée</li>
</ul></li>
<li>Pour de gros jeux de données avec beaucoup de colonnes, <code>glimpse</code> (dans tidyverse) permet d’afficher en long toutes les colonnes et de prévisualiser leur contenu : afficher le jeu de données <code>glimpse(P2012T1)</code>. > l’intérêt c’est de l’afficher en long au lieu de l’afficher en large, du coup on voit les 1res lignes de toutes les variables en s’adaptant à la taille de l’écran.</li>
</ul>
</div>
<div id="préparer-des-tidy-data" class="section level2">
<h2><span class="header-section-number">12.3</span> Préparer des tidy data</h2>
<ul>
<li>Packages utiles pour faire du “tidy” data : <code>dplyr</code> et <code>tidyr</code>
<ul>
<li>Ce qui n’est pas utile dans le script, peut être mis en commentaires. Permet de tout rééexecuter sans lancer des fonctions inutiles et sans perdre la trace de leur utilité.</li>
<li>Ces packages travaillent tous avec des données tabulaires avec une syntaxe unifiée : des verbes.</li>
</ul></li>
<li>Ces verbes sont articulés avec un “pipe”, un tuyau et si on les mets bout à bout, cela donne un pipeline :)
<ul>
<li>Le symbole <code>%>%</code> représente le pipe dans R (raccourci clavier pour l’écrire dans Rstudio : Ctrl + Shift + M ou Pomme + Shift + M)</li>
<li>L’intérêt c’est de se débarrasser des colonnes inutiles, ou plutôt de ne conserver que celles dont on a besoin</li>
</ul></li>
<li>Avec <code>select</code> : on indique les colonnes qu’on veut garder et celles dont on veut se débarrasser</li>
</ul>
<p>Colonnes pas utiles : libellé du département (on pourra les retrouver, redondant avec code du département), nom de la commune (redondant avec code de la commune), blancs et nuls (on pourra le recalculer)</p>