-
Notifications
You must be signed in to change notification settings - Fork 4
/
ds.tex
9371 lines (7720 loc) · 392 KB
/
ds.tex
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
\documentclass[12pt,]{krantz}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\else % if luatex or xelatex
\ifxetex
\usepackage{mathspec}
\else
\usepackage{fontspec}
\fi
\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\setmonofont[Mapping=tex-ansi,Scale=0.7]{Source Code Pro}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\PassOptionsToPackage{hyphens}{url} % url is loaded by hyperref
\usepackage[unicode=true]{hyperref}
\PassOptionsToPackage{usenames,dvipsnames}{color} % color is loaded by hyperref
\hypersetup{
pdftitle={An Introduction to Statistical Programming Methods with R},
pdfauthor={Matthew Beckman, Stéphane Guerrier, Justin Lee, Roberto Molinari \& Samuel Orso},
colorlinks=true,
linkcolor=Maroon,
citecolor=Blue,
urlcolor=Blue,
breaklinks=true}
\urlstyle{same} % don't use monospace font for urls
\usepackage{natbib}
\bibliographystyle{apalike}
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.27,0.27,0.27}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.27,0.27,0.27}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.06,0.06,0.06}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.06,0.06,0.06}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.06,0.06,0.06}{#1}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.5,0.5,0.5}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.5,0.5,0.5}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.5,0.5,0.5}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.5,0.5,0.5}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textbf{\textit{#1}}}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textbf{\textit{#1}}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textbf{\textit{#1}}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.27,0.27,0.27}{\textbf{#1}}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.43,0.43,0.43}{\textbf{#1}}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.61,0.61,0.61}{#1}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textbf{\textit{#1}}}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textbf{\textit{#1}}}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.33,0.33,0.33}{#1}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.14,0.14,0.14}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\usepackage{longtable,booktabs}
% Fix footnotes in tables (requires footnote package)
\IfFileExists{footnote.sty}{\usepackage{footnote}\makesavenoteenv{long table}}{}
\usepackage{graphicx,grffile}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{5}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\usepackage{booktabs}
\usepackage{longtable}
\usepackage[bf,singlelinecheck=off]{caption}
% \setmainfont[UprightFeatures={SmallCapsFont=AlegreyaSC-Regular}]{Alegreya}
\usepackage{framed,color}
\definecolor{shadecolor}{RGB}{248,248,248}
\renewcommand{\textfraction}{0.05}
\renewcommand{\topfraction}{0.8}
\renewcommand{\bottomfraction}{0.8}
\renewcommand{\floatpagefraction}{0.75}
\renewenvironment{quote}{\begin{VF}}{\end{VF}}
\let\oldhref\href
\renewcommand{\href}[2]{#2\footnote{\url{#1}}}
\ifxetex
\usepackage{letltxmacro}
\setlength{\XeTeXLinkMargin}{1pt}
\LetLtxMacro\SavedIncludeGraphics\includegraphics
\def\includegraphics#1#{% #1 catches optional stuff (star/opt. arg.)
\IncludeGraphicsAux{#1}%
}%
\newcommand*{\IncludeGraphicsAux}[2]{%
\XeTeXLinkBox{%
\SavedIncludeGraphics#1{#2}%
}%
}%
\fi
\makeatletter
\newenvironment{kframe}{%
\medskip{}
\setlength{\fboxsep}{.8em}
\def\at@end@of@kframe{}%
\ifinner\ifhmode%
\def\at@end@of@kframe{\end{minipage}}%
\begin{minipage}{\columnwidth}%
\fi\fi%
\def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
\colorbox{shadecolor}{##1}\hskip-\fboxsep
% There is no \\@totalrightmargin, so:
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
\MakeFramed {\advance\hsize-\width
\@totalleftmargin\z@ \linewidth\hsize
\@setminipage}}%
{\par\unskip\endMakeFramed%
\at@end@of@kframe}
\makeatother
\makeatletter
\@ifundefined{Shaded}{
}{\renewenvironment{Shaded}{\begin{kframe}}{\end{kframe}}}
\makeatother
\newenvironment{rmdblock}[1]
{
\begin{itemize}
\renewcommand{\labelitemi}{
\raisebox{-.7\height}[0pt][0pt]{
{\setkeys{Gin}{width=3em,keepaspectratio}\includegraphics{images/#1.png}}
}
}
\setlength{\fboxsep}{1em}
\begin{kframe}
\item
}
{
\end{kframe}
\end{itemize}
}
\newenvironment{rmdnote}
{\begin{rmdblock}{note}}
{\end{rmdblock}}
\newenvironment{rmdcaution}
{\begin{rmdblock}{caution}}
{\end{rmdblock}}
\newenvironment{rmdimportant}
{\begin{rmdblock}{important}}
{\end{rmdblock}}
\newenvironment{rmdtip}
{\begin{rmdblock}{tip}}
{\end{rmdblock}}
\newenvironment{rmdwarning}
{\begin{rmdblock}{warning}}
{\end{rmdblock}}
\usepackage{makeidx}
\makeindex
\urlstyle{tt}
\usepackage{amsthm}
\makeatletter
\def\thm@space@setup{%
\thm@preskip=8pt plus 2pt minus 4pt
\thm@postskip=\thm@preskip
}
\makeatother
\frontmatter
\title{An Introduction to Statistical Programming Methods with R}
\author{Matthew Beckman, Stéphane Guerrier, Justin Lee, Roberto Molinari \&
Samuel Orso}
\date{2018-10-03}
\let\BeginKnitrBlock\begin \let\EndKnitrBlock\end
\begin{document}
\maketitle
%\cleardoublepage\newpage\thispagestyle{empty}\null
%\cleardoublepage\newpage\thispagestyle{empty}\null
%\cleardoublepage\newpage
\thispagestyle{empty}
% \begin{center}
% \includegraphics{images/dedication.pdf}
% \end{center}
\setlength{\abovedisplayskip}{-5pt}
\setlength{\abovedisplayshortskip}{-5pt}
{
\hypersetup{linkcolor=black}
\setcounter{tocdepth}{1}
\tableofcontents
}
\listoftables
\listoffigures
\chapter{Introduction}\label{introduction}
This book is an early version of an ongoing project to equip students
with the basic knowledge to master ``statistical programming'' with R.
The statistical software \texttt{R} has come into prominence due to its
flexibility as an efficient language that builds a bridge between
software development and data analysis. For example, one strength of
\texttt{R} is the facility to develop and quickly adapt to the different
needs coming from the data management and analysis community while at
the same time making use of other languages in order to deliver
computationally efficient solutions. This book intends to present an
approachable framework to statistical programming and software
development using the wide variety of tools made available through
\texttt{R}, from method-specific packages to version control programs.
The general goals of the book are therefore the following:
\begin{itemize}
\tightlist
\item
introduce tools and workflow for reproducible research (R/RStudio,
Git/GitHub, etc.);
\item
introduce principles of tidy data and tools for data wrangling;
\item
exploit data structures to appropriately manage data, computer memory
and computations;
\item
data manipulation through controls, instructions, and tailored
functions;
\item
develop new software tools including functions, Shiny applications,
and packages;
\item
manage software development process including version control,
documentation (with embedded code), and dissemination for other users.
\end{itemize}
The rest of this introductory chapter will present the R software by
explaining why it is used for this book and describing the basic
notations and tools that need to be known in order to better grasp its
contents.
\BeginKnitrBlock{rmdimportant}
This document is \textbf{under development} and it is therefore
preferable to always access the text online to be sure you are using the
most up-to-date version. Due to its current development, you may
encounter errors ranging from broken code to typos or poorly explained
topics. If you do, please let us know! Simply add an issue to the GitHub
repository used for this document (accessed here
\url{https://github.com/SMAC-Group/ds/issues}) and we will make the
changes as soon as possible. In addition, once you have learned
RMarkdown and GitHub, feel free to make a pull request to offer bug
fixes or corrections!
\EndKnitrBlock{rmdimportant}
\includegraphics{images/diagram.png}
To demonstrate our goals, we will try to implement the process that is
mentioned in the diagram above. In many cases, an input (e.g.~data
source) is provided, and then we process, explore, and/or manipulate the
data with R. We then may communicate our findings through websites,
reports, slides, etc. using some combination of RMarkdown, R, and/or
Shiny. This process is not always sequential as we often have new ideas
or observations at any stage and begin exploring again.
\section{\texorpdfstring{\texttt{R} and
\texttt{RStudio}}{R and RStudio}}\label{r-and-rstudio}
The statistical computing language
\href{https://cran.r-project.org/}{\texttt{R}} has become commonplace
for many applications in industry, government, and academia. Having
started as an open-source language to make available different
statistics and analytical tools to researchers and the public, it
steadily developed into one of the major software languages which not
only allows to develop up-to-date, sound, and flexible analytical tools,
but also to include these tools within a framework which is
well-integrated with other important tools. The latter is amplified
thanks to the development of the
\href{https://www.rstudio.com/}{RStudio} interface which provides a
pleasant and functional user-interface for \texttt{R} as well as an
efficient Integrated Development Environment (IDE) in which different
programming languages, web-applications and other important tools are
readily available to the user. In order to illustrate the relationship
between R \& RStudio in statistical programming, one might think of a
car analogy in which R would be the drivetrain and chassis while RStudio
adds comfortable seats and air conditioning. R is doing most of the
work, and the user can basically get where they want to go using R
without RStudio. RStudio is generally is making you more comfortable
while you use R, but you won't get very far using RStudio without R.
\subsection{\texorpdfstring{Getting started with
\texttt{R}}{Getting started with R}}\label{getting-started-with-r}
Since \texttt{R} is a free and open-source software, you may simply
download it from the following link:
\begin{itemize}
\tightlist
\item
\href{https://cran.r-project.org/}{\texttt{R}:
https://cran.r-project.org/}
\end{itemize}
While \texttt{R} certainly can be used ``as is'' for many purposes, we
strongly recommend using an IDE called RStudio. There are several
versions of RStudio for different users (RStudio Desktop, Commercial,
Server, etc.). The free RStudio Desktop version is sufficient for our
purposes. RStudio can downloaded from the following link:
\begin{itemize}
\tightlist
\item
\href{https://www.rstudio.com/}{RStudio: https://www.rstudio.com/}
\end{itemize}
\BeginKnitrBlock{rmdimportant}
You cannot use \texttt{RStudio} without having installed \texttt{R} on
your computer.
\EndKnitrBlock{rmdimportant}
\subsection{\texorpdfstring{Why \texttt{R}?}{Why R?}}\label{why-r}
There are many reasons to use \texttt{R}. Two compelling reasons are
that R is both free as in ``free pizza'', and free as in ``free
speech''. Free--like ``free pizza''--means that there is never a need to
pay for any part of the R software, or contributed packages (i.e.~add-on
modules). Free--like ``free speech''--means that there are very few
restrictions on how R can be used or barriers to those who would like to
contribute packages (i.e.~add-on modules).
The fact that is a free and open-source software does not necessarily
imply that it is a good software (although it is also that). The reason
why this is an important feature consists in the fact that the results
of any code or program developed in the \texttt{R} environment can
easily be replicated therefore ensuring accessibility and transparency
for the general user. More importantly however, this replicability of
results is also accompanied by a wide variety of packages that are made
available through the \texttt{R} environment in which users can find a
diversity of codes, functions, and features that are designed to tackle
a large amount of programming and analytical tasks. Moreover, new
packages are relatively simple to create and are extremely useful for
code-sharing purposes since they enclose the codes, functions, and
external dependencies that allow anyone to easily and efficiently
install these features. Additionally, these accessibility and
code-sharing features have established \texttt{R} as a platform for
development and dissemination of cutting-edge tools directly from the
developer to the end-user.
\subsection{About RStudio}\label{about-rstudio}
\texttt{RStudio} is a customizable IDE for the \texttt{R} enviornment
where the user can have easy access to plots, data, help, files, objects
and many other features that are useful to work efficiently with
\texttt{R}. For the most part, \texttt{RStudio} provides nearly
everything the \texttt{R} user will need in a self-contained, and
well-organized environment. Moreover, it is possible to create
``projects'' in which it is possible to create a dedicated environment
space for sets of specific functions and files aimed to deal with
various tasks.
Below is short video demonstrating a basic introduction of RStudio and
some of its elements.
In addition, \texttt{RStudio} provides embedded functionality to utilize
collaborative version-control software including GitHub \& Subversion as
well as a set of powerful tools to save and communicate results (whether
they be simulations, data analysis, or presenting and making available a
new package to other users). Some examples of these tools are
\texttt{Rmarkdown} which can be used respectively to integrate written
narrative with embedded \texttt{R} code and other content, as well as
and \texttt{Shiny\ Web\ Apps} which can provide an interactive
user-friendly interface that permits a user to actively engage with a
wide variety of tools built in \texttt{R} without the need to encounter
raw \texttt{R} code. GitHub and \texttt{Rmarkdown} will be the object of
a more in-depth description in the first chapters of this book in order
to provide the reader with the version-control and annotation tools that
can be useful for the following chapters of this book.
\subsection{Conventions}\label{conventions}
Throughout this book, \texttt{R} code will be typeset using a
\texttt{monospace} font which is syntax highlighted. For example:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a <-}\StringTok{ }\NormalTok{pi}
\NormalTok{b <-}\StringTok{ }\FloatTok{0.5}
\KeywordTok{sin}\NormalTok{(a}\OperatorTok{*}\NormalTok{b)}
\end{Highlighting}
\end{Shaded}
Similarly, \texttt{R} output lines (that usally appear in your Console)
will begin with \texttt{\#\#} and will not be syntax highlighted. The
output of the above example is the following:
\begin{verbatim}
## [1] 1
\end{verbatim}
Aside from \texttt{R} code and output, this book will also insert boxes
in order to draw the reader's attention to important, curious, or
otherwise informative details. An example of these boxes was seen at the
beginning of this introduction where an important aspect was pointed out
to the reader regarding the ``under construction'' nature of this book.
Therefore the following boxes and symbols can be used to represent
information of different nature:
\BeginKnitrBlock{rmdnote}
This is a \textbf{note} that could be interesting or useful to the
reader.
\EndKnitrBlock{rmdnote}
\BeginKnitrBlock{rmdtip}
This is a \textbf{tip} for implementing content from this book.
\EndKnitrBlock{rmdtip}
\BeginKnitrBlock{rmdimportant}
This highlights \textbf{important information}.
\EndKnitrBlock{rmdimportant}
\BeginKnitrBlock{rmdcaution}
This is a \textbf{caution} to help the reader avoid minor problems.
\EndKnitrBlock{rmdcaution}
\BeginKnitrBlock{rmdwarning}
This is a \textbf{warning} to help the reader avoid significant
problems.
\EndKnitrBlock{rmdwarning}
\subsection{Getting help}\label{getting-help}
In the previous section we presented some examples on how \texttt{R} can
be used as a calculator and we have already seen several functions such
as \texttt{sqrt()} or \texttt{log()}. To obtain documentation about a
function in \texttt{R}, simply put a question mark in front of the
function name (or just type \texttt{help()} around the function name),
or use the search bar on the ``Help'' tab in your RStudio window, and
its documentation will be displayed. For example, if you are interested
in learning about the function \texttt{log()} you could simply type:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{?log}
\end{Highlighting}
\end{Shaded}
which will display something similar to:
\begin{figure}
\centering
\includegraphics{images/example-log-help.png}
\caption{}
\end{figure}
The \texttt{R} documentation is written by the author of the package.
For mainstream packages in widespread use, the documentation is almost
always quite good, but in some cases it can be quite technical,
difficult to interpret, and possibly incomplete. In these cases, the
best solution to understand a function is to search for help on any
search engine. Often a simple search like ``side by side boxplots in R''
or ``side by side boxplots in ggplot2'' will produce many useful
results. The search results often include user forums such as
``CrossValidated'' or ``StackExchange'' in which the questions you have
about a function have probably already been asked and answered by many
other users.
\BeginKnitrBlock{rmdtip}
You can often use the error message to search for answers about a
problem you may have with a function.
\EndKnitrBlock{rmdtip}
\subsection{Installing packages}\label{installing-packages}
\texttt{R} comes with a number of built-in functions but one of its main
strengths is that there is a large number of packages on an
ever-increasing range of subjects available for you to install. These
packages provide additional functions, features and data to the R
environement. If you want to do something in \texttt{R} that is not
available by default, there is a good chance that there are packages
that will respond to your needs. In this case, an appropriate way to
find a package in \texttt{R} is to use the search option in the CRAN
repository which is the official network of file-transfer protocols and
web-servers that store updated versions of code and documentation for
\texttt{R} (see CRAN website). Another general approach to find a
package in \texttt{R} is simply to use a search engine in which to type
the keywords of the tools you are looking for followed by ``R package''.
\texttt{R} packages can be installed in various ways but the most widely
used approach is through the \texttt{install.packages()} function.
Another way is to use the ``Tools -\textgreater{} Install
Packages\ldots{}'' path from the dropdown menus in \texttt{RStudio} or
clicking on the ``install'' button in the ``Packages'' pane in the
RStudio environment. The \texttt{install.packages()} function is very
straight-forward and transcends any platform for the \texttt{R}
environment. It is noteworthy that this approach assumes that the
desired package(s) are available within the CRAN repository. This is
very often the case, but there is a growing number of packages that are
under-development or completed and are made available through other
repositories. In the latter setting, Chapter 02 will show other ways of
installing packages from a commonly used repository called ``GitHub''.
Sticking momentarily to the packages available in the CRAN repository,
the use of the \texttt{install.packages()} is quite simple. For example,
if you want to install the package \texttt{devtools} you can simply
write:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{install.packages}\NormalTok{(}\StringTok{"devtools"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Once a package is installed it is not directly usable within your
\texttt{R} session. To do so you will have to ``load'' the package into
your current \texttt{R} session which is generally done through the
function \texttt{library()}. For example, after having installed the
\texttt{devtools} package, in order to use it within your session you
would write:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(devtools)}
\end{Highlighting}
\end{Shaded}
Once this is done, all the functions and documentation of this package
are available and can be used within your current session. However, once
you close your \texttt{R} session, all loaded packages will be closed
and you will have to load them again if you want to use them in a new
\texttt{R} session.
\BeginKnitrBlock{rmdnote}
Please notice that although packages need to be loaded at each session
if you want to use them, they need to be installed only once. The only
exception to this rule is when you need to update the package or
reinstall it for some reason.
\EndKnitrBlock{rmdnote}
One of the main packages that is required for this class would be our
STAT 297 package, that contains all the necessary packages and functions
that will be utilized in this book. Run the following code to install
the package directly from GitHub.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{install_github}\NormalTok{(}\StringTok{"SMAC-Group/stat297"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\BeginKnitrBlock{rmdwarning}
The STAT 297 package is required for use of many features in this book.
\EndKnitrBlock{rmdwarning}
\subsection{Additional References}\label{additional-references}
There are many more elements in RStudio, and we encourage you to use the
\href{https://www.rstudio.com/wp-content/uploads/2016/01/rstudio-IDE-cheatsheet.pdf}{RStudio
Cheatsheet} as a reference.
\section{\texorpdfstring{Basic Probability and Statistics with
\texttt{R}}{Basic Probability and Statistics with R}}\label{basic-probability-and-statistics-with-r}
The \texttt{R} environment provides an up-to-date and efficient
programming language to develop different tools and applications.
Nevertheless, its main functionality lies in the core statistical
framework and tools that consistute the basis of this language. Indeed,
this book aims at introducing and describing the methods and approaches
of statistical programming which therefore require a basic knowledge of
Probability and Statistics in order to grasp the logic and usefulness of
the features presented in this book.
For this reason, we will briefly take the reader through some of the
basic functions that are available within \texttt{R} to obtain
probabilities based on parametric distributions, compute summary
statistics and understand basic data structures. The latter is just an
introduction and a more in-depth description of different data
structures will be given in a future chapter.
\subsection{Simple calculations}\label{simple-calculations}
Since the \texttt{R} environment can serve as an advanced calculator, it
is worth noting this also allows for simple calculations. In the table
below we show a few examples of such calculations where the first column
gives a mathematical expression (calculation), the second gives the
equivalent of this expression in \texttt{R} and finally in the third
column we can find the result that is output from \texttt{R}.
\begin{longtable}[]{@{}lll@{}}
\toprule
Math. & R & Result\tabularnewline
\midrule
\endhead
2+2 & \texttt{2+2} & \texttt{4}\tabularnewline
\(\frac{4}{2}\) & \texttt{4/2} & \texttt{2}\tabularnewline
\(3 \cdot 2^{-0.8}\) & \texttt{3*2\^{}(-0.8)} &
\texttt{1.723048}\tabularnewline
\(\sqrt{2}\) & \texttt{sqrt(2)} & \texttt{1.414214}\tabularnewline
\(\pi\) & \texttt{pi} & \texttt{3.141593}\tabularnewline
\(\ln(2)\) & \texttt{log(2)} & \texttt{0.6931472}\tabularnewline
\(\log_{3}(9)\) & \texttt{log(9,\ base\ =\ 3)} &
\texttt{2}\tabularnewline
\(e^{1.1}\) & \texttt{exp(1.1)} & \texttt{3.004166}\tabularnewline
\(\cos(\sqrt{0.9})\) & \texttt{cos(sqrt(0.9))} &
\texttt{0.5827536}\tabularnewline
\bottomrule
\end{longtable}
\subsection{Probability Distributions}\label{probability-distributions}
Probability distributions can be uniquely characterized by different
functions such as, for example, their density or distribution functions.
Based on these it is possible to compute theoretical quantiles and also
randomly sample observations from them. Replacing the \texttt{R} syntax
for a given probability distribution with the general syntax
\texttt{name}, all these functions and calculations are made available
in \texttt{R} through the built-in functions:
\begin{itemize}
\tightlist
\item
\texttt{dname} calculates the value of the density function (pdf);
\item
\texttt{pname} calculates the value of the distribution function
(cdf);
\item
\texttt{qname} calculates the value of the theoretical quantile;
\item
\texttt{rname} generates a random sample from a particular
distribution.
\end{itemize}
Note that, when using these functions in practice, \texttt{name} is
replaced with the syntax used in \texttt{R} to denote a specific
probability distribution. For example, if we wish to deal with a Uniform
probability distribution, then the syntax \texttt{name} is replaced by
\texttt{unif} and, furthering the example, to randomly generate
observations from a uniform distribution the function to use will be
therefore \texttt{runif}. \texttt{R} allows to make use of these
functions for a wide variety of probability distributions that include,
but are not limited to: Gaussian (or Normal), Binomial, Chi-square,
Exponential, F-distribution, Geometric, Poisson, Student-t and Uniform.
In order to get an idea of how these functions can be used, below is an
example of a problem that can be solved using them.
\subsubsection{Example: Normal Test Scores of College Entrance
Exam}\label{example-normal-test-scores-of-college-entrance-exam}
Assume that the test scores of a college entrance exam follows a Normal
distribution. Furthermore, suppose that the mean test score is 70 and
that the standard deviation is 15. How would we find the percentage of
students scoring 90 or more in this exam?
In this case, we consider a random variable \(X\) that is normally
distributed as follows: \(X \sim N(\mu=70, \sigma^2=225)\) where \(\mu\)
and \(\sigma^2\) represent the mean and variance of the distribution
respectively. Since we are looking for the probability of students
scoring higher than 90, we are interested in finding
\(\mathbb{P}(X > x=90)\) and therefore we look at the upper tail of the
Normal distribution. To find this probability we need the distribution
function (\texttt{pname}) for which we therefore replace \texttt{name}
with the \texttt{R} syntax for the Normal distribution: \texttt{norm}.
The distribution function in \texttt{R} has various parameters to be
specified in order to compute a probability which, at least for the
Normal distribution, can be found by typing \texttt{?pnorm} in the
Console and are:
\begin{itemize}
\tightlist
\item
\texttt{q}: the quantile we are interested in (e.g.~90);
\item
\texttt{mean}: the mean of the distribution (e.g.~70);
\item
\texttt{sd}: the standard deviation of the distribution (e.g.~15);
\item
\texttt{lower.tail}: a boolean determining whether to compute the
probability of being smaller than the given quantile (i.e.
\(\mathbb{P}(X \leq x)\)) which requires the default argument
\texttt{TRUE} or larger (i.e. \(\mathbb{P}(X > x)\)) which requires to
specify the argument \texttt{FALSE}.
\end{itemize}
Knowing these arguments, it is now possible to compute the probability
we are interested in as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{pnorm}\NormalTok{(}\DataTypeTok{q =} \DecValTok{90}\NormalTok{, }\DataTypeTok{mean =} \DecValTok{70}\NormalTok{, }\DataTypeTok{sd =} \DecValTok{15}\NormalTok{, }\DataTypeTok{lower.tail =} \OtherTok{FALSE}\NormalTok{) }
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 0.09121122
\end{verbatim}
As we can see from the output, there is roughly a 9\% probability of
students scoring 90 or more on the exam.
\subsection{Summary Statistics}\label{summary-statistics}
While the previous functions deal with theoretical distributions, it is
also necessary to deal with real data from which we would like to
extract information. Supposing--as is often the case in applied
statistics--we don't know from which distribution it is generated, we
would be interested in understanding the behavior of the data in order
to eventually identify a distribution and estimate its parameters.
The use of certain functions varies according to the nature of the
inputs since these can be, for example, numerical or factors.
\subsubsection{Numerical Input}\label{numerical-input}
A first step in analysing numerical inputs is given by computing summary
statistics of the data which, in this section, we can generally denote
as \texttt{x} (we will discuss the structure of this data more in detail
in the following chapters). For central tendency or spread statistics of
a numerical input, we can use the following \texttt{R} built-in
functions:
\begin{itemize}
\tightlist
\item
\texttt{mean} calculates the mean of an input \texttt{x};
\item
\texttt{median} calculates the median of an input \texttt{x};
\item
\texttt{var} calculates the variance of an input \texttt{x};
\item
\texttt{sd} calculates the standard deviation of an input \texttt{x};
\item
\texttt{IQR} calculates the interquartile range of an input
\texttt{x};
\item
\texttt{min} calculates the minimum value of an input \texttt{x};
\item
\texttt{max} calculates the maximum value of an input \texttt{x};
\item
\texttt{range} returns a vector containing the minimum and maximum of
all given arguments;
\item
\texttt{summary} returns a vector containing a mixture of the above
functions (i.e.~mean, median, first and third quartile, minimum,
maximum).
\end{itemize}
\subsubsection{Factor Input}\label{factor-input}
If the data of interest is a factor with different categories or levels,
then different summaries are more appropriate. For example, for a factor
input we can extract counts and percentages to summarize the variable by
using \texttt{table}. Using functions and data structures that will be
described in the following chapters, below we create an example dataset
with 90 observations of three different colors: 20 being
\texttt{Yellow}, 10 being \texttt{Green} and 50 being \texttt{Blue}. We
then apply the \texttt{table} function to it:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{table}\NormalTok{(}\KeywordTok{as.factor}\NormalTok{(}\KeywordTok{c}\NormalTok{(}\KeywordTok{rep}\NormalTok{(}\StringTok{"Yellow"}\NormalTok{, }\DecValTok{20}\NormalTok{), }\KeywordTok{rep}\NormalTok{(}\StringTok{"Green"}\NormalTok{, }\DecValTok{10}\NormalTok{), }\KeywordTok{rep}\NormalTok{(}\StringTok{"Blue"}\NormalTok{, }\DecValTok{50}\NormalTok{))))}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
##
## Blue Green Yellow
## 50 10 20
\end{verbatim}
By doing so we obtain a frequency (count) table of the colors.
\subsubsection{Dataset Inputs}\label{dataset-inputs}
In many cases, when dealing with data we are actually dealing with
datasets (see Chapter 03) where variables of different nature are
aligned together (usually in columns). For datasets there is another
convenient way to get simple summary statistics which consists in
applying the function \texttt{summary} to the dataset itself (instead of
simply a numerical input as seen earlier).
As an example, let us explore the
\href{https://en.wikipedia.org/wiki/Iris_flower_data_set}{Iris} flower
dataset contained in the \texttt{R} built-in \texttt{datasets} package.
The data set consists of 50 samples from each of three species of Iris
(Setosa, Virginica and Versicolor). Four features were measured from
each sample consisting in the length and the width (in centimeters) of
the both sepals and petals. This dataset is widely used as an example
since it was used by Fisher to develop a linear discriminant model based
on which he intended to distinguish the three species from each other
using combinations of these four features.
Using this dataset, let us use the \texttt{summary} function on it to
output the minimum, first quartile and thrid quartile, median, mean and
maximum statistics (for the numerical variables in the dataset) and
frequency counts (for factor inputs).
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{summary}\NormalTok{(iris)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100
## 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
## Median :5.800 Median :3.000 Median :4.350 Median :1.300
## Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
## 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
## Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
## Species
## setosa :50
## versicolor:50
## virginica :50
##
##
##
\end{verbatim}
\section{Main References}\label{main-references}
This is not the first (or the last) book that has been written
explaining and describing statistical programming in \texttt{R}. Indeed,
this can be seen as a book that brings together and reorganizes
information and material from other sources structuring and tailoring it
to a course in basic statistical programming. The main references (which
are far from being an exhaustive review of literature) that can be used
to have a more in-depth view of different aspects treated in this book
are:
\begin{itemize}
\tightlist
\item
\citet{wickham2014advanced} : a more technical and advanced
introduction to \texttt{R};
\item
\citet{wickham2015packages} : basic building blocks of building
packages in \texttt{R};
\item
\citet{xie2015} : an overview of document generation in \texttt{R};
\end{itemize}
\section{License}\label{license}
You can redistribute it and/or modify this book under the terms of the
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
License (CC BY-NC-SA) 4.0 License.
\part{Foundation}\label{part-foundation}
\chapter{RMarkdown}\label{rmarkdown}
RMarkdown is a framework that provides a literate programming format for
data science. It can be used to save and execute R code within RStudio
and also as a simple formatting syntax for authoring HTML, PDF, ODT,
RTF, and MS Word documents as well as seamless transitions between
available formats. The name ``markdown'' is an intentional contrast to
other ``markup'' languages--e.g., hypertext markup language
(HTML)--which require syntax that can be quite difficult to decipher for
the uninitiated. One aim of the markdown paradigm is a syntax that is as
human-readable as possible. ``RMarkdown'' is an implementation of the
``markdown'' language designed to accommodate embedded \texttt{R} code.
\subsection*{\texorpdfstring{What is \textbf{literate} programming
?}{What is literate programming ?}}\label{what-is-literate-programming}
\addcontentsline{toc}{subsection}{What is \textbf{literate} programming
?}
Literate programming is the notion for programmers of adding narrative
context with code to produce documentation for the program
simultaneously. Consequently, it is possible to read through the code
with explanations so that any viewer can follow through the
presentation. RMarkdown offers a simple tool that allows to create
reports or presentation slides in a reproducible manner with collateral
advantages such as avoiding repetitive tasks by, for example, changing
all figures when data are updated.
\subsection*{\texorpdfstring{What is \textbf{reproducible} research
?}{What is reproducible research ?}}\label{what-is-reproducible-research}
\addcontentsline{toc}{subsection}{What is \textbf{reproducible} research
?}
Reproducible research or reproducible analysis is the notion that an
experiment's whole process, including collecting data, performing
analysis and producing output, can be reproduced the same way by someone
else. Building non-reproducible experiments has been a problem both in
research and in the industry, and having such an issue highly decreases
the credibility of the authors' findings and, potentially, the authors
themselves. In essence, allowing for reproducible research implies that
anyone could run the code (knit the document, etc.) and obtain the same
exact results as the original research and RMarkdown is commonly used to
address this issue.
Below is a short video showing a basic overview of RMarkdown.
Below, we have created a framework application that you can use to test
out different RMarkdown functions. Experiment with different R Markdown
elements and utilize it to practice building and knitting HTML output.
You can access the online versions here:
\begin{itemize}
\tightlist
\item
\href{http://shiny.science.psu.edu/szg279/rmd/}{RMarkdown Web}
\item
\href{http://shiny.science.psu.edu/szg279/rmd_mini/}{RMarkdown Mobile}
\end{itemize}
or simply run it within the \texttt{stat297} package by using either
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# RMarkdown Web}
\NormalTok{stat297}\OperatorTok{::}\KeywordTok{runShiny}\NormalTok{(}\StringTok{'rmd'}\NormalTok{)}
\CommentTok{# RMarkdown Mobile}
\NormalTok{stat297}\OperatorTok{::}\KeywordTok{runShiny}\NormalTok{(}\StringTok{'rmd_mini'}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\section{Create an R Markdown file in
RStudio}\label{create-an-r-markdown-file-in-rstudio}
Within RStudio, click \texttt{File} → \texttt{New\ File} →
\texttt{R\ Markdown}. Give the file a title and the author (your name)
and select the default output, HTML. We can change this later so don't
worry about it for the moment.
\includegraphics{images/rmd_new.png}
An RMarkdown is a plain text file that contains three different aspects:
\begin{itemize}
\tightlist
\item
YAML metadata
\item
Text
\item
Code Chunks
\end{itemize}
\section{YAML Metadata}\label{yaml-metadata}
YAML stands for \emph{YAML Ain't Markup Language} and is used to specify
document configurations and properties such as name, date, output
format, etc. The (optional) YAML header is surrounded before and after
by ``---'' on a dedicated line.
\includegraphics{images/rmd_yaml.png}
You can also include additional formatting
\href{http://RMarkdown.rstudio.com/html_document_format.html}{options}