-
Notifications
You must be signed in to change notification settings - Fork 32
/
modern_R.tex
18418 lines (15207 loc) · 817 KB
/
modern_R.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
% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[
]{article}
\usepackage{amsmath,amssymb}
\usepackage{lmodern}
\usepackage{iftex}
\ifPDFTeX
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provide euro and other symbols
\else % if luatex or xetex
\usepackage{unicode-math}
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
\KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\usepackage[margin=1in]{geometry}
\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{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\usepackage{longtable,booktabs,array}
\usepackage{calc} % for calculating minipage widths
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
\usepackage{graphicx}
\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}
% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{5}
\usepackage{booktabs}
\ifLuaTeX
\usepackage{selnolig} % disable illegal ligatures
\fi
\usepackage[]{natbib}
\bibliographystyle{apalike}
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\urlstyle{same} % disable monospaced font for URLs
\hypersetup{
pdftitle={Modern R with the tidyverse},
pdfauthor={Bruno Rodrigues},
hidelinks,
pdfcreator={LaTeX via pandoc}}
\title{Modern R with the tidyverse}
\author{Bruno Rodrigues}
\date{2022-10-13}
\begin{document}
\maketitle
{
\setcounter{tocdepth}{2}
\tableofcontents
}
\hypertarget{preface}{%
\section*{Preface}\label{preface}}
\addcontentsline{toc}{section}{Preface}
\hypertarget{note-to-the-reader}{%
\subsection*{Note to the reader}\label{note-to-the-reader}}
\addcontentsline{toc}{subsection}{Note to the reader}
I have been working on this on and off for the past 4 years or so. In 2022, I have updated the
contents of the book to reflect updates introduced with R 4.1 and in several packages (especially
those from the \texttt{\{tidyverse\}}). I have also cut some content that I think is not that useful,
especially in later chapters.
This book is still being written. Chapters 1 to 8 are almost ready, but more content is being added
(especially to chapter 8). 9 and 10 are empty for now. Some exercises might be at the wrong place
too and more are coming.
You can purchase an ebook version of this book on \href{https://leanpub.com/modern_tidyverse}{leanpub}.
The version on leanpub is quite out of date, so if you buy it, it's really just to send some money
my money, so many thanks for that! You can also support me by \href{https://www.buymeacoffee.com/brodriguesco}{buying me a
coffee} or
\href{https://www.paypal.me/brodriguesco}{paypal.me}.
\hypertarget{what-is-r}{%
\subsection*{What is R?}\label{what-is-r}}
\addcontentsline{toc}{subsection}{What is R?}
Read R's official answer to this question
\href{https://cran.r-project.org/doc/FAQ/R-FAQ.html\#What-is-R_003f}{here}. To make it short: R is a
multi-paradigm (procedural, imperative, object-oriented and functional)\footnote{In this book we are going
to focus on R's functional programming capabilities} programming language that
focuses on applications in \emph{statistics}. By \emph{statistics} I mean any field that uses statistics such
as official statistics, economics, finance, data science, machine learning, etc. For the sake of
simplicity, I will use the word ``statistics'' as a general term that encompasses all these fields and
disciplines for the remainder of this book.
\hypertarget{who-is-this-book-for}{%
\subsection*{Who is this book for?}\label{who-is-this-book-for}}
\addcontentsline{toc}{subsection}{Who is this book for?}
This book can be useful to different audiences. If you have never used R in your life, and want
to start, start with Chapter 1 of this book. Chapter 1 to 3 are the very basics, and should be
easy to follow up to Chapter 7.
Starting with Chapter 7, it gets more technical, and will be harder to follow. But I suggest
you keep on going, and do not hesitate to contact me for help if you struggle! Chapter 7
is also where you can start if you are already familiar with R \textbf{and} the \texttt{\{tidyverse\}}, but not
functional programming. If you are familiar with R but not the \texttt{\{tidyverse\}} (or have no clue
what the \texttt{\{tidyverse\}} is), then you can start with Chapter 4. If you are familiar with R, the
\texttt{\{tidyverse\}} and functional programming, you might still be interested in this book, especially
Chapter 9 and 10, which deal with package development and further advanced topics respectively.
\hypertarget{why-this-book}{%
\subsection*{Why this book?}\label{why-this-book}}
\addcontentsline{toc}{subsection}{Why this book?}
This book is first and foremost for myself. This book is the result of years of using and teaching
R at university and then at my jobs. During my university time, I wrote some notes to help me
teach R and which I shared with my students. These are still the basis of Chapter 2. Then, once
I had left university, and continued using R at my first ``real'' job, I wrote another book that
dealt mostly with package development and functional programming. This book is now merged to this
one and is the basis of Chapters 9 and 10. During these years at my first
job, I was also tasked with teaching R. By that time, I was already quite familiar with the
\texttt{\{tidyverse\}} so I wrote a lot of notes that were internal and adapted for the audience of my
first job. These are now the basis of Chapters 3 to 8.
Then, during all these years, I kept blogging about R, and reading blogs and further books. All
this knowledge is condensed here, so if you are familiar with my blog, you'll definitely recognize
a lot of my blog posts in here. So this book is first and foremost for me, because I need to write
all of this down in a central place. So because my target audience is myself, this book is free. If
you find it useful, and are in the mood of buying me a coffee, you can, but if this book is not
useful to you, no harm done (unless you paid for it before reading it, in which case, I am sorry
to have wasted your time). But I am quite sure you'll find some of the things written here useful,
regardless of your current experience level with R.
\hypertarget{why-modern-r}{%
\subsection*{\texorpdfstring{Why \emph{modern} R?}{Why modern R?}}\label{why-modern-r}}
\addcontentsline{toc}{subsection}{Why \emph{modern} R?}
\emph{Modern} R instead of ``just'' R because we are going to learn how to use modern packages (mostly
those from the \href{https://www.tidyverse.org/}{tidyverse}) and concepts, such as functional
programming (which is quite an old concept actually, but one that came into fashion recently). R is
derived from S, which is a programming language that has roots in FORTRAN and other languages too.
If you learned R at university, you've probably learned to use it as you would have used FORTRAN;
very long scripts where data are represented as matrices and where row-wise (or column-wise)
operations are implemented with \texttt{for} loops. There's nothing wrong with that, mind you, but R
was also influenced by Scheme and Common Lisp, which are functional programming languages.
In my opinion, functional programming is a programming paradigm that works really well when dealing
with statistical problems. This is because programming in a functional style is just like
writing math. For instance, suppose you want to sum all the elements of a vector. In mathematical
notation, you would write something like:
\[
\sum_{i = 1}^{100} x_{i}
\]
where \(x\) is a vector of length 100. Solving this using a loop would look something like this:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{res }\OtherTok{\textless{}{-}} \DecValTok{0}
\ControlFlowTok{for}\NormalTok{(i }\ControlFlowTok{in} \DecValTok{1}\SpecialCharTok{:}\FunctionTok{length}\NormalTok{(x))\{}
\NormalTok{ res }\OtherTok{\textless{}{-}}\NormalTok{ x[i] }\SpecialCharTok{+}\NormalTok{ res}
\NormalTok{\}}
\end{Highlighting}
\end{Shaded}
This does not look like the math notation at all! You have to define a variable that will hold
the result outside of the loop, and then you have to define \texttt{res} as something plus \texttt{res} inside
the body of the loop. This is really unnatural. The functional programming approach is much
easier:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{Reduce}\NormalTok{(}\StringTok{\textasciigrave{}}\AttributeTok{+}\StringTok{\textasciigrave{}}\NormalTok{, x)}
\end{Highlighting}
\end{Shaded}
We will learn about \texttt{Reduce()} later (to be more precise, we will learn about \texttt{purrr::reduce()},
the ``tidy'' version of \texttt{Reduce()}), but already you see that the notation looks a lot more
like the mathematical notation.
At its core, functional programming uses functions, and functions are so-called \emph{first
class} objects in R, which means that there is nothing special about them\ldots{} you can pass them to
other functions, create functions that return functions and do any kind of operation on them just as
with any other object. This means that functions in R are extremely powerful and flexible tools.
In the first part of the book, we are going to use functions that are already available in R, and
then use those available in packages, mostly those from the \texttt{tidyverse}. The \texttt{tidyverse} is a
collection of packages developed by \href{http://hadley.nz/}{Hadley Wickham}, and several of his colleagues
at RStudio, Inc.~By using the packages from the \texttt{tidyverse} and R's built-in functional programming
capabilities, we can write code that is faster and easier to explain to colleagues, and also easier
to maintain. This also means that you might have to change your expectations and what you know
already from R, if you learned it at University but haven't touched it in a long time. For example
for and while loops, are relegated to chapter 8. This does not mean that you will have to wait for
8 chapter to know how to repeat instructions \emph{N} times, but that \emph{for} and \emph{while} loops are tools that
are very useful for very specific situations that will be discussed at that point.
In the second part of the book, we are going to move from using R to solve statistical problems to
developing with R. We are going to learn about creating your own package. If you do not know what
packages are, don't worry, this will be discussed just below.
\hypertarget{what-is-rstudio}{%
\subsection*{What is RStudio?}\label{what-is-rstudio}}
\addcontentsline{toc}{subsection}{What is RStudio?}
RStudio is a modern IDE that makes writing R code easier. The first thing we are going to learn is
how to use it.
R and RStudio are both open source: this means that the source code is freely available on
the internet and contributions by anyone are welcome and integrated; provided they are meaningful
and useful.
\hypertarget{what-to-expect-from-this-book}{%
\subsection*{What to expect from this book?}\label{what-to-expect-from-this-book}}
\addcontentsline{toc}{subsection}{What to expect from this book?}
The idea of Chapters 1 to 7 is to make you efficient with R as quickly as possible, especially if
you already have prior programming knowledge. Starting with Chapter 8 you will learn more advanced
topics, especially programming with R. R is a programming language, and you can't write
``programming language'' without ``language''. And just as you wouldn't expect to learn
French, Portuguese or Icelandic by reading a single book, you shouldn't expect to become fluent in R
by reading a single book, not even by reading 10 books. Programming is an art which requires a lot of
practice. \href{http://www.norvig.com/21-days.html}{Teach yourself programming in 10 years} is a blog
post written by Peter Norvig which explains that just as with any craft, mastering programming
takes time. And even if you don't need or want to become an expert in R, if you wish to use R
effectively and in a way that ultimately saves you time, you need to have some fluency in it, and
this only comes by continuing to learn about the language, and most importantly practicing. If you
keep using R every day, you'll definitely become very fluent. To stay informed about developments of
the language, and the latest news, I advise you read blogs, especially
\href{https://www.r-bloggers.com/}{R-bloggers} which aggregates blog posts by more than 750 blogs
discussing R.
So what you can expect from this book is that this book is not the only one you should read.
\hypertarget{prerequisites}{%
\subsection*{Prerequisites}\label{prerequisites}}
\addcontentsline{toc}{subsection}{Prerequisites}
R and RStudio are the two main pieces of software that we are going to use. R is the programming
language and RStudio is a modern IDE for it. You can use R without RStudio; but you cannot use
RStudio without R.
If you wish to install R and RStudio at home to follow the examples in this book you can do it as
both pieces of software are available free of charge (paid options for RStudio exist, for companies
that need technical support). Installation is simple, but operating system dependent. To download
and install R for Windows, follow \href{https://cloud.r-project.org/bin/windows/base/}{this link}.
For macOS, follow \href{https://cloud.r-project.org/bin/macosx/}{this one}. If you run a GNU+Linux
distribution, you can install R using the system's package manager. On Ubuntu, install \texttt{r-base}.
For RStudio, look for your operating system \href{https://www.rstudio.com/products/rstudio/download/\#download}{here}.
\hypertarget{what-are-packages}{%
\subsection*{What are packages?}\label{what-are-packages}}
\addcontentsline{toc}{subsection}{What are packages?}
There is one more step; we are going to install some packages. Packages are additional pieces of
code that can be installed from within R with the following function: \texttt{install.packages()}. These
packages extend R's capabilities significantly, and are probably one of the main reasons R is so
popular. As of November 2018, R has over 13000 packages.
To install the packages we need, first open RStudio and then copy and paste this line in the console:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{install.packages}\NormalTok{(}\FunctionTok{c}\NormalTok{(}\StringTok{"tidyverse"}\NormalTok{, }\StringTok{"rsample"}\NormalTok{, }\StringTok{"recipes"}\NormalTok{, }\StringTok{"blogdown"}\NormalTok{ ,}\StringTok{"yardstick"}\NormalTok{, }\StringTok{"parsnip"}\NormalTok{, }\StringTok{"plm"}\NormalTok{, }\StringTok{"pwt9"}\NormalTok{, }
\StringTok{"checkpoint"}\NormalTok{, }\StringTok{"Ecdat"}\NormalTok{, }\StringTok{"ggthemes"}\NormalTok{, }\StringTok{"ggfortify"}\NormalTok{, }\StringTok{"margins"}\NormalTok{, }\StringTok{"janitor"}\NormalTok{, }\StringTok{"rio"}\NormalTok{, }\StringTok{"stopwords"}\NormalTok{,}
\StringTok{"colourpicker"}\NormalTok{, }\StringTok{"glmnet"}\NormalTok{, }\StringTok{"lhs"}\NormalTok{, }\StringTok{"mlrMBO"}\NormalTok{, }\StringTok{"mlbench"}\NormalTok{, }\StringTok{"ranger"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\includegraphics[width=14.9in]{pics/install_packages}
or go to the \textbf{Packages} pane and then click on \emph{Install}:
\includegraphics{pics/rstudio_install_packages.gif}
\hypertarget{the-author}{%
\subsection*{The author}\label{the-author}}
\addcontentsline{toc}{subsection}{The author}
My name is Bruno Rodrigues and I program almost exclusively in R and have been teaching some R
courses for a few years now. I first started teaching for students at the University of Strasbourg
while working on my PhD. I hold a PhD in economics, with a focus on quantitative methods.
I'm currently head of the statistics department of the Ministry of Higher education and Research
in Luxembourg, and before that worked as a manager in the data science team of PWC Luxembourg.
This book is an adaptation of notes I've used in the past during my time as a teacher, but also
a lot of things I've learned about R since I left academia.
In my free time I like cooking, working out and \href{https://www.brodrigues.co}{blogging}, while listening to
\href{http://www.fipradio.fr/player}{Fip} or
\href{https://chillsky.com/listen/}{Chillsky Radio}.
I also like to get my butt handed to me by playing roguelikes
such as \href{http://nethack.wikia.com/wiki/NetHack}{NetHack}, for which I wrote a
\href{https://github.com/b-rodrigues/nethack}{package} that contains functions to analyze the data that
is saved on your computer after you win or lose (it will be lose 99\% of the time) the game.
You can follow me on \href{https://www.twitter.com/brodriguesco}{twitter}, I tweet mostly about R or
what's happening in Luxembourg.
\hypertarget{getting-to-know-rstudio}{%
\section{Getting to know RStudio}\label{getting-to-know-rstudio}}
RStudio is a company that develops and maintains several products. Their best-known product is
an IDE (Integrated development environment) for the R programming language, also called RStudio.
You can install RStudio by visiting this \href{https://www.rstudio.com/products/rstudio/download/}{link}.
There is also a server version that can be used to have a centralized version of R within, say, a
company. RStudio, the company, also develops \href{https://shiny.rstudio.com/}{Shiny}, a package to
create full-fledged web-apps. I am not going to cover Shiny in this book, since there's already
\href{http://shiny.rstudio.com/tutorial/}{a lot} of material that you can learn from.
Once you have installed RStudio, launch it and let's go through the interface together.
\hypertarget{panes}{%
\subsection{Panes}\label{panes}}
RStudio is divided into different panes. Each pane has a specific function. The gif below shows
some of these panes:
\includegraphics{pics/rstudio_panes.gif}
Take some time to look around what each pane shows you. Some panes are empty; for example the \emph{Plots}
pane or the \emph{Viewer} pane. \emph{Plots} shows you the plots you make. You can browse the plots and save
them. We will see this in more detail in a later chapter. \emph{Viewer} shows you previews of documents
that you generate with R. More on this later.
\hypertarget{console}{%
\subsection{Console}\label{console}}
The \emph{Console} pane is where you can execute R code. Write the following in the console:
\begin{Shaded}
\begin{Highlighting}[]
\DecValTok{2} \SpecialCharTok{+} \DecValTok{3}
\end{Highlighting}
\end{Shaded}
and you'll get the answer, \texttt{5}. However, do not write a lot of lines in the console. It is better
write your code inside a script. Output is also shown inside the console.
\hypertarget{scripts}{%
\subsection{Scripts}\label{scripts}}
Look at the gif below:
\includegraphics{pics/rstudio_new_script.gif}
In this gif, we see the user creating a new R script. R scripts are simple text files that hold R
code. Think of \texttt{.do} files in STATA or \texttt{.c} files for C. R scripts have the extension \texttt{.r} or \texttt{.R}.
It is possible to create a lot of other files. We'll take a look at \texttt{R\ Markdown} files in Chapter 11.
\hypertarget{the-help-pane}{%
\subsubsection{The help pane}\label{the-help-pane}}
The \emph{Help} pane allows you to consult documentation for functions or packages. The gif below shows
how it works:
\includegraphics{pics/rstudio_help.gif}
you can also access help using the following syntax: \texttt{?lm}. This will bring up the documentation for
the function \texttt{lm()}. You can also type \texttt{??lm} which will look for the string \texttt{lm} in every package.
\hypertarget{the-environment-pane}{%
\subsubsection{The Environment pane}\label{the-environment-pane}}
The \emph{Environment} pane shows every object created in the current section. It is especially useful
if you have defined lists or have loaded data into R as it makes it easy to explore these more
complex objects.
\hypertarget{options}{%
\subsection{Options}\label{options}}
It is also possible to customize RStudio's look and feel:
\includegraphics{pics/rstudio_options.gif}
Take some time to go through the options.
\hypertarget{keyboard-shortcuts}{%
\subsection{Keyboard shortcuts}\label{keyboard-shortcuts}}
It is a good idea to familiarize yourself with at least some keyboard shortcuts. This is more
convenient than having to move the mouse around:
\includegraphics{pics/rstudio_shortcuts.gif}
If there is only one keyboard shortcut you need to know, it's \texttt{Ctrl-Enter} that executes a line of code
from your script. However, these other shortcuts are also worth knowing:
\begin{itemize}
\tightlist
\item
\texttt{CTRL-ALT-R}: run entire script
\item
\texttt{CTRL-ALT-UP\ or\ DOWN}: make cursor taller or shorter, allowing you to edit multiple lines at the same time
\item
\texttt{CTRL-F}: Search and replace
\item
\texttt{ALT-UP\ or\ DOWN}: Move line up or down
\item
\texttt{CTRL-SHIFT-C}: Comment/uncomment line
\item
\texttt{ALT-SHIFT-K}: Bring up the list of keyboard shortcuts
\item
\texttt{CTRL-SHIFT-M}: Insert the pipe operator (\texttt{\%\textgreater{}\%}, more on this later)
\item
\texttt{CTRL-S}: Save script
\end{itemize}
This is just a few keyboard shortcuts that I personally find useful. However, I strongly advise you
to learn and use whatever shortcuts are useful and feel natural to you!
\hypertarget{projects}{%
\subsection{Projects}\label{projects}}
One of the best features of RStudio are projects. Creating a project is simple; the gif below
shows how you can create a project and how you can switch between projects.
\includegraphics{pics/rstudio_projects.gif}
Projects make a lot of things easier, such as managing paths. More on this in the chapter about
reading data. Another useful feature of projects is that the scripts you open in project A will
stay open even if you switch to another project B, and then switch back to the project A again.
You can also use version control (with git) inside a project. Version control is very useful, but
I won't discuss it here. You can find a lot of resources online to get you started with git.
\hypertarget{history}{%
\subsection{History}\label{history}}
The \emph{History} pane saves all the previous lines you executed. You can then select these lines and
send them back to the console or the script.
\includegraphics{pics/rstudio_history.gif}
\hypertarget{plots}{%
\subsection{Plots}\label{plots}}
All the plots you make during a session are visible in the \emph{Plots} pane. From there, you can
export them in different formats.
\includegraphics{pics/rstudio_plots.gif}
The plots shown in the gif are made using basic R functions. Later, we will learn how to make nicer
looking plots using the package \texttt{ggplot2}.
\hypertarget{addins}{%
\subsection{Addins}\label{addins}}
Some packages install addins, which are accessible through the addins button:
\includegraphics[width=17.08in]{pics/rstudio_addins}
These addins make it easier to use some functions and you can read more about them \href{https://rstudio.github.io/rstudioaddins/\#overview}{here}.
My favorite addins are the ones you get when installing the \texttt{\{datapasta\}} package. Read more about
it \href{https://github.com/MilesMcBain/datapasta}{here}.
There are other panes that I will not discuss here, but you will naturally discover their use as you
go. For example, we will discuss the \emph{Build} pane in Chapter 11.
\hypertarget{packages}{%
\subsection{Packages}\label{packages}}
You can think of packages as addons that extend R's core functionality. You can browse all available
packages on \href{https://cloud.r-project.org/}{CRAN}. To make it easier to find what you might be
interested in, you can also browse the \href{https://cloud.r-project.org/web/views/}{CRAN Task Views}.
Each package has a landing page that summarises its dependencies, version number etc. For example,
for the \texttt{dplyr} package: \url{https://cran.r-project.org/web/packages/dplyr/index.html}.
Take a look at the \emph{Downloads} section, and especially at the Reference Manual and Vignettes:
\includegraphics[width=13.49in]{pics/packages_vignette}
Vignettes are valuable documents; inside vignettes, the purpose of the package is explained in
plain English, usually with accompanying examples. The reference manuals list the available functions
inside the packages. You can also find vignettes from within Rstudio:
\includegraphics{pics/rstudio_vignette.gif}
Go to the \emph{Packages} pane and click on the package you're interested in. Then you can consult the
help for the functions that come with the package as well as the package's vignettes.
Once you installed a package, you have to load it before you can use it. To load packages you use the
\texttt{library()} function:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(dplyr)}
\FunctionTok{library}\NormalTok{(janitor)}
\CommentTok{\# and so on...}
\end{Highlighting}
\end{Shaded}
If you only need to use one single function once, you don't need to load an entire package. You can
write the following:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dplyr}\SpecialCharTok{::}\FunctionTok{full\_join}\NormalTok{(A, B)}
\end{Highlighting}
\end{Shaded}
using the \texttt{::} operator, you can access functions from packages without having to load the whole
package beforehand.
It is possible and easy to create your own packages. This is useful if you have to write a lot of
functions that you use daily. We will lean about that, in Chapter 10.
\hypertarget{exercises}{%
\subsection{Exercises}\label{exercises}}
\hypertarget{exercise-1}{%
\subsubsection*{Exercise 1}\label{exercise-1}}
\addcontentsline{toc}{subsubsection}{Exercise 1}
Change the look and feel of RStudio to suit your tastes! I personally like to move the console
to the right and use a dark theme. Take some 5 minutes to customize it and browse through all the options.
\hypertarget{objects-their-classes-and-types-and-useful-r-functions-to-get-you-started}{%
\section{Objects, their classes and types, and useful R functions to get you started}\label{objects-their-classes-and-types-and-useful-r-functions-to-get-you-started}}
All objects in R have a given \emph{type}. You already know most of them, as these types are also used
in mathematics. Integers, floating point numbers (floats), matrices, etc, are all objects you
are already familiar with. But R has other, maybe lesser known data types (that you can find in a
lot of other programming languages) that you need to become familiar with. But first, we need to
learn how to assign a value to a variable. This can be done in two ways:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \DecValTok{3}
\end{Highlighting}
\end{Shaded}
or
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{=} \DecValTok{3}
\end{Highlighting}
\end{Shaded}
in very practical terms, there is no difference between the two. I prefer using \texttt{\textless{}-} for assigning
values to variables and reserve \texttt{=} for passing arguments to functions, for example:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{spam }\OtherTok{\textless{}{-}} \FunctionTok{mean}\NormalTok{(}\AttributeTok{x =} \FunctionTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{2}\NormalTok{,}\DecValTok{3}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
I think this is less confusing than:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{spam }\OtherTok{=} \FunctionTok{mean}\NormalTok{(}\AttributeTok{x =} \FunctionTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{2}\NormalTok{,}\DecValTok{3}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
but as I explained above you can use whatever you feel most comfortable with.
\hypertarget{the-numeric-class}{%
\subsection{\texorpdfstring{The \texttt{numeric} class}{The numeric class}}\label{the-numeric-class}}
To define single numbers, you can do the following:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \DecValTok{3}
\end{Highlighting}
\end{Shaded}
The \texttt{class()} function allows you to check the class of an object:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "numeric"
\end{verbatim}
Decimals are defined with the character \texttt{.}:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \FloatTok{3.14}
\end{Highlighting}
\end{Shaded}
R also supports integers. If you find yourself in a situation where you explicitly need an integer
and not a floating point number, you can use the following:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \FunctionTok{as.integer}\NormalTok{(}\DecValTok{3}\NormalTok{)}
\FunctionTok{class}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "integer"
\end{verbatim}
The \texttt{as.integer()} function is very useful, because it converts its argument into an integer. There
is a whole family of \texttt{as.*()} functions. To convert \texttt{a} into a floating point number again:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(}\FunctionTok{as.numeric}\NormalTok{(a))}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "numeric"
\end{verbatim}
There is also \texttt{is.numeric()} which tests whether a number is of the \texttt{numeric} class:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{is.numeric}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] TRUE
\end{verbatim}
It is also possible to create an integer using \texttt{L}:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}}\NormalTok{ 5L}
\FunctionTok{class}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "integer"
\end{verbatim}
Another way to convert this integer back to a floating point number is to use \texttt{as.double()} instead of
as numeric:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(}\FunctionTok{as.double}\NormalTok{(a))}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "numeric"
\end{verbatim}
The functions prefixed with \texttt{is.*} and \texttt{as.*} are quite useful, there is one for any of the supported types in R, such
as \texttt{as/is.character()}, \texttt{as/is.factor()}, etc\ldots{}
\hypertarget{the-character-class}{%
\subsection{\texorpdfstring{The \texttt{character} class}{The character class}}\label{the-character-class}}
Use \texttt{"\ "} to define characters (called strings in other programming languages):
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \StringTok{"this is a string"}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "character"
\end{verbatim}
To convert something to a character you can use the \texttt{as.character()} function:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \FloatTok{4.392}
\FunctionTok{class}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "numeric"
\end{verbatim}
Now let's convert it:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(}\FunctionTok{as.character}\NormalTok{(a))}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "character"
\end{verbatim}
It is also possible to convert a character to a numeric:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \StringTok{"4.392"}
\FunctionTok{class}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "character"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(}\FunctionTok{as.numeric}\NormalTok{(a))}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "numeric"
\end{verbatim}
But this only works if it makes sense:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \StringTok{"this won\textquotesingle{}t work, chief"}
\FunctionTok{class}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "character"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{as.numeric}\NormalTok{(a)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Warning: NAs introduced by coercion
\end{verbatim}
\begin{verbatim}
## [1] NA
\end{verbatim}
A very nice package to work with characters is \texttt{\{stringr\}}, which is also part of the \texttt{\{tidyverse\}}.
\hypertarget{the-factor-class}{%
\subsection{\texorpdfstring{The \texttt{factor} class}{The factor class}}\label{the-factor-class}}
Factors look like characters, but are very different. They are the representation of categorical
variables. A \texttt{\{tidyverse\}} package to work with factors is \texttt{\{forcats\}}. You would rarely use
factor variables outside of datasets, so for now, it is enough to know that this class exists.
We are going to learn more about factor variables in Chapter 4, by using the \texttt{\{forcats\}} package.
\hypertarget{the-date-class}{%
\subsection{\texorpdfstring{The \texttt{Date} class}{The Date class}}\label{the-date-class}}
Dates also look like characters, but are very different too:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{as.Date}\NormalTok{(}\StringTok{"2019/03/19"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "2019-03-19"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(}\FunctionTok{as.Date}\NormalTok{(}\StringTok{"2019/03/19"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "Date"
\end{verbatim}
Manipulating dates and time can be tricky, but thankfully there's a \texttt{\{tidyverse\}} package for that,
called \texttt{\{lubridate\}}. We are going to go over this package in Chapter 4.
\hypertarget{the-logical-class}{%
\subsection{\texorpdfstring{The \texttt{logical} class}{The logical class}}\label{the-logical-class}}
This is the class of predicates, expressions that evaluate to \emph{true} or \emph{false}. For example, if you type:
\begin{Shaded}
\begin{Highlighting}[]
\DecValTok{4} \SpecialCharTok{\textgreater{}} \DecValTok{3}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] TRUE
\end{verbatim}
R returns \texttt{TRUE}, which is an object of class \texttt{logical}:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{k }\OtherTok{\textless{}{-}} \DecValTok{4} \SpecialCharTok{\textgreater{}} \DecValTok{3}
\FunctionTok{class}\NormalTok{(k)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "logical"
\end{verbatim}
In other programming languages, \texttt{logical}s are often called \texttt{bool}s. A \texttt{logical} variable can only have
two values, either \texttt{TRUE} or \texttt{FALSE}. You can test the truthiness of a variable with \texttt{isTRUE()}:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{k }\OtherTok{\textless{}{-}} \DecValTok{4} \SpecialCharTok{\textgreater{}} \DecValTok{3}
\FunctionTok{isTRUE}\NormalTok{(k)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] TRUE
\end{verbatim}
How can you test if a variable is false? There is not a \texttt{isFALSE()} function (at least not without having
to load a package containing this function), but there is way to do it:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{k }\OtherTok{\textless{}{-}} \DecValTok{4} \SpecialCharTok{\textgreater{}} \DecValTok{3}
\SpecialCharTok{!}\FunctionTok{isTRUE}\NormalTok{(k)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] FALSE
\end{verbatim}
The \texttt{!} operator indicates negation, so the above expression could be translated as \emph{is k not TRUE?}.
There are other operators for boolean algebra, namely \texttt{\&,\ \&\&,\ \textbar{},\ \textbar{}\textbar{}}. \texttt{\&} means \emph{and} and \texttt{\textbar{}} stands for \emph{or}.
You might be wondering what the difference between \texttt{\&} and \texttt{\&\&} is? Or between \texttt{\textbar{}} and \texttt{\textbar{}\textbar{}}? \texttt{\&} and
\texttt{\textbar{}} work on vectors, doing pairwise comparisons:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{one }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{)}
\NormalTok{two }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{)}
\NormalTok{one }\SpecialCharTok{\&}\NormalTok{ two}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] FALSE FALSE TRUE FALSE
\end{verbatim}
Compare this to the \texttt{\&\&} operator:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{one }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{)}
\NormalTok{two }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{)}
\NormalTok{one }\SpecialCharTok{\&\&}\NormalTok{ two}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Warning in one && two: 'length(x) = 4 > 1' in coercion to 'logical(1)'
## Warning in one && two: 'length(x) = 4 > 1' in coercion to 'logical(1)'
\end{verbatim}
\begin{verbatim}
## [1] FALSE
\end{verbatim}
The \texttt{\&\&} and \texttt{\textbar{}\textbar{}} operators only compare the first element of the vectors and stop as soon as a the return
value can be safely determined. This is called short-circuiting. Consider the following:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{one }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{)}
\NormalTok{two }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{)}
\NormalTok{three }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{)}
\NormalTok{one }\SpecialCharTok{\&\&}\NormalTok{ two }\SpecialCharTok{\&\&}\NormalTok{ three}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Warning in one && two: 'length(x) = 4 > 1' in coercion to 'logical(1)'
## Warning in one && two: 'length(x) = 4 > 1' in coercion to 'logical(1)'
\end{verbatim}
\begin{verbatim}
## [1] FALSE
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{one }\SpecialCharTok{||}\NormalTok{ two }\SpecialCharTok{||}\NormalTok{ three}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Warning in one || two: 'length(x) = 4 > 1' in coercion to 'logical(1)'
\end{verbatim}
\begin{verbatim}
## [1] TRUE
\end{verbatim}
The \texttt{\textbar{}\textbar{}} operator stops as soon it evaluates to \texttt{TRUE} whereas the \texttt{\&\&} stops as soon as it evaluates to \texttt{FALSE}.
Personally, I rarely use \texttt{\textbar{}\textbar{}} or \texttt{\&\&} because I get confused. I find using \texttt{\textbar{}} or \texttt{\&} in combination with the
\texttt{all()} or \texttt{any()} functions much more useful:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{one }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{)}
\NormalTok{two }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{)}