-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintro2R.tex
10173 lines (8118 loc) · 413 KB
/
intro2R.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[
]{book}
\usepackage{lmodern}
\usepackage{amsmath}
\usepackage{ifxetex,ifluatex}
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provide euro and other symbols
\usepackage{amssymb}
\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}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\hypersetup{
pdftitle={Introduction to R for health data analysis},
pdfauthor={Ehsan Karim, An Hoang and Yang Qu},
hidelinks,
pdfcreator={LaTeX via pandoc}}
\urlstyle{same} % disable monospaced font for URLs
\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}
\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}
<script type="text/javascript">
// toggle visibility of R source blocks in R Markdown output
function toggle_R() {
var x = document.getElementsByClassName('r');
if (x.length == 0) return;
function toggle_vis(o) {
var d = o.style.display;
o.style.display = (d == 'block' || d == '') ? 'none':'block';
}
for (i = 0; i < x.length; i++) {
var y = x[i];
if (y.tagName.toLowerCase() === 'pre') toggle_vis(y);
}
var elem = document.getElementById("myButton1");
if (elem.value === "Hide Global") elem.value = "Show Global";
else elem.value = "Hide Global";
}
document.write('<input onclick="toggle_R();" type="button" value="Hide Global" id="myButton1" style="position: absolute; top: 10%; right: 2%; z-index: 200"></input>')
</script>
\ifluatex
\usepackage{selnolig} % disable illegal ligatures
\fi
\usepackage[]{natbib}
\bibliographystyle{apalike}
\newlength{\cslhangindent}
\setlength{\cslhangindent}{1.5em}
\newlength{\csllabelwidth}
\setlength{\csllabelwidth}{3em}
\newenvironment{CSLReferences}[2] % #1 hanging-ident, #2 entry spacing
{% don't indent paragraphs
\setlength{\parindent}{0pt}
% turn on hanging indent if param 1 is 1
\ifodd #1 \everypar{\setlength{\hangindent}{\cslhangindent}}\ignorespaces\fi
% set entry spacing
\ifnum #2 > 0
\setlength{\parskip}{#2\baselineskip}
\fi
}%
{}
\usepackage{calc}
\newcommand{\CSLBlock}[1]{#1\hfill\break}
\newcommand{\CSLLeftMargin}[1]{\parbox[t]{\csllabelwidth}{#1}}
\newcommand{\CSLRightInline}[1]{\parbox[t]{\linewidth - \csllabelwidth}{#1}\break}
\newcommand{\CSLIndent}[1]{\hspace{\cslhangindent}#1}
\title{Introduction to R for health data analysis}
\author{Ehsan Karim, An Hoang and Yang Qu}
\date{2021-07-25}
\begin{document}
\maketitle
{
\setcounter{tocdepth}{1}
\tableofcontents
}
\hypertarget{preface}{%
\chapter*{Preface}\label{preface}}
\addcontentsline{toc}{chapter}{Preface}
This is a R tutorial for those who are not familiar with data wrangling. For providing some practical introduction to data wrangling, NHANES datasets will be used as examples in this tutorial.
\hypertarget{main-references}{%
\section*{Main references}\label{main-references}}
\addcontentsline{toc}{section}{Main references}
\begin{itemize}
\tightlist
\item
Overall reference \citet{wickham2016r}
\end{itemize}
\hypertarget{version-history}{%
\section*{Version history}\label{version-history}}
\addcontentsline{toc}{section}{Version history}
This tutorial was initially created by a team supported by worklearn program in 2021 May-August (during Covid-19 pandemic). Initial team members included An Hoang and Yang Qu, working under the supervision of Ehsan Karim.
\hypertarget{contributor-list}{%
\section*{Contributor list}\label{contributor-list}}
\addcontentsline{toc}{section}{Contributor list}
\begin{itemize}
\tightlist
\item
An Hoang (forestry, UBC)
\item
Yang Qu (statistics, UBC)
\end{itemize}
\hypertarget{prerequisites}{%
\subsection*{Prerequisites}\label{prerequisites}}
\addcontentsline{toc}{subsection}{Prerequisites}
None.
\hypertarget{comments}{%
\subsection*{Comments}\label{comments}}
\addcontentsline{toc}{subsection}{Comments}
For any comments regarding this document, reach out to \href{http://ehsank.com/}{me}.
\hypertarget{r-and-rstudio-set-up}{%
\chapter{R and RStudio set up}\label{r-and-rstudio-set-up}}
\hypertarget{instructions}{%
\section{INSTRUCTIONS}\label{instructions}}
This tutorial is aiming to introduce you to R and RStudio. It will guide you to download and install R and RStudio and walk you through the main components in RStudio. Follow this tutorial step-by-step and finish setting up R and RStudio before the next tutorial.
Accompanying this tutorial is \textbf{a short \href{https://forms.gle/Xf1AfoGaxhwrWRQ38}{Google quiz}} for your own self-assessment. The instructions of this tutorial will clearly indicate when you should answer which question.
\hypertarget{learning-objectives}{%
\section{LEARNING OBJECTIVES}\label{learning-objectives}}
\begin{itemize}
\item
Understand the difference between R and RStudio
\item
Download and install R
\item
Download and install RStudio
\item
Be familiar with the main components in RStudio
\end{itemize}
\hypertarget{what-is-r}{%
\section{1. What is R}\label{what-is-r}}
R is a language and enviroment for statistical computing and graphics. It is commonly used in borh academia and industry.
It is:
\begin{itemize}
\item
Free and open source
\item
Easy to learn and use
\item
Good compatibility - can be used in Windows, macOS, and Linux
\end{itemize}
For more information about R, check out this \href{https://www.r-project.org/about.html}{website}.
\textbf{DO QUESTION 1 OF THE QUIZ NOW}
\textgreater{} True of False: R is a programming language
\hypertarget{what-is-rstudio}{%
\section{2. What is RStudio}\label{what-is-rstudio}}
RStudio is not a language - is an IDE (Integrated Development Environment) for R. It hae two versions available: RStudio desktop and RStudio Server. We will use RStudio desktop in this tutorial.
There are lots of available IDEs for R. The reason why we chooes RStudio is that it has a fancy GUI and required features that makes working with R much easier and more efficient.
\textbf{DO QUESTION 2 OF THE QUIZ NOW}
\textgreater{} True of False: RStudio is a programming language which is similar to R
\hypertarget{download-and-install-r}{%
\section{3. Download and install R}\label{download-and-install-r}}
\begin{itemize}
\item
Go to \url{https://www.r-project.org/} and click on \textbf{download R}
\item
Choose CRAN location based on your geological location
\item
Download R based on your operating system and choose the latest release version (it is Python 3.9.5 for now)
\item
Open the downloaded package and follow the instruction there to finish the installation
\end{itemize}
\hypertarget{download-and-install-rstudio}{%
\section{4. Download and install RStudio}\label{download-and-install-rstudio}}
\textbf{Make sure you downloaded and installed R before doing the following steps}
\begin{itemize}
\item
Go to \url{https://www.rstudio.com/products/rstudio/download/} and download the RStudio Desktop
\item
Open the downloaded file and follow the instruction there to finish the installation
\end{itemize}
\hypertarget{rstudio-basics}{%
\section{5. RStudio basics}\label{rstudio-basics}}
\begin{figure}
\centering
\includegraphics{https://i.imgur.com/TKTocvu.png}
\caption{image}
\end{figure}
RStudio have 4 main components:
\begin{itemize}
\item
Script (top left)
\begin{itemize}
\item
the Script is where you write the R code
\item
you can save the script as a \texttt{.R} file
\end{itemize}
\item
Console (bottom left)
\begin{itemize}
\item
the console is where the R code being executed
\item
Output (except graphs and plots) will be shown after code executed
\end{itemize}
\item
Workspace (top right)
\begin{itemize}
\item
all objects in the current working environments including variables, data, and functions are listed here with a brief display of their corresponding values.
\item
you can import other workspaces, save the current workspace, and clean up the current workspace
\item
R workspace file ends with \texttt{.RData}
\end{itemize}
\item
Files, Plots, Packages, Help (bottom right)
\begin{itemize}
\item
Files is the place to view the Files and to set Working Directory
\item
Plots gives a preview of plot - it is the place where graphical output will be displayed
\item
Packages is the place to install/view/update packages
\item
Help is the place to get help about R
\end{itemize}
\end{itemize}
\textbf{DO QUESTION 3 OF THE QUIZ NOW}
\textgreater{} In RStudio, where do you write your R code if you don't want it be saved?
\textbf{DO QUESTION 4 OF THE QUIZ NOW}
\textgreater{} In RStudio, where do you write your R code if you do want it be saved?
\textbf{DO QUESTION 5 OF THE QUIZ NOW}
\textgreater{} What type is the saved R code file?
\textbf{DO QUESTION 6 OF THE QUIZ NOW}
\textgreater{} In RStudio, where is your R code executed?
\textbf{DO QUESTION 7 OF THE QUIZ NOW}
\textgreater{} In RStudio, where is numerical output displayed?
\textbf{DO QUESTION 8 OF THE QUIZ NOW}
\textgreater{} In RStudio, where is graphical output displayed?
\textbf{DO QUESTION 9 OF THE QUIZ NOW}
\textgreater{} In RStudio, where are variables, data, functions stored?
\textbf{DO QUESTION 10 OF THE QUIZ NOW}
\textgreater{} What type is the workspace file?
\textbf{DO QUESTION 11 OF THE QUIZ NOW}
\textgreater{} Is there a way to find the details about functions and packages in RStudio?
\hypertarget{takeaways}{%
\section{TAKEAWAYS}\label{takeaways}}
By the end of this tutorial, you should be able to set up R and RStudio successfully. Please feel free to reach out if you have any issues with the set ups.
Before we proceed to the next tutorial, make sure that you're familiar with the RStudio GUI and features.
\hypertarget{introduction-to-r}{%
\chapter{Introduction to R}\label{introduction-to-r}}
\hypertarget{instructions-1}{%
\section{INSTRUCTIONS}\label{instructions-1}}
This tutorial will introduce you to the basics of the language of R. We will cover how to set up our working environment, mathematical and logical operators, the most common data types in R, explore a simple dataset, write an R function as well as how to seek for help within and outside of R.
Accompanying this tutorial is \textbf{a short \href{https://forms.gle/P5x4pRK39xrA9EJR9}{Google quiz}} for your own self-assessment. The instructions of this tutorial will clearly indicate when you should answer which question.
\hypertarget{learning-objectives-1}{%
\section{LEARNING OBJECTIVES}\label{learning-objectives-1}}
\begin{itemize}
\tightlist
\item
Be familiar with the basic procedures for setting up an R session with functions such as \texttt{getwd()}, \texttt{setwd()}, \texttt{dir()}, \texttt{install.packages()}, and \texttt{library()}.
\item
Understand the very basic of how and when to use arithmetic and logical operators in R.
\item
Be familiar with the most common types of data in R including string, vector, data frame, and list.
\item
Explore a dataset using basic Base R functions.
\item
Know how to write a new function in R.
\item
Be comfortable with and know how to seek for help within and outside of R.
\end{itemize}
\hypertarget{set-up-basics}{%
\section{1. SET UP BASICS}\label{set-up-basics}}
\hypertarget{working-directory}{%
\subsection{Working Directory}\label{working-directory}}
One of the most important function in R is \texttt{getwd()}, or ``get working directory''. The output of this code is the pathway of your current R file. Interestingly, \texttt{getwd()} does not have any argument. In other words, you do not have to type anything in the \texttt{()}.
It is highly recommended that all of your files (the R file, any data files, images, etc) be in the same directory. This will make your project much more organized and your life a lot easier when we get into more complicated data analysis that involves more data files.
By default, your working directory is whatever folder your current R file is in.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{getwd}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "C:/Users/ehsan/Documents/GitHub/intro2R"
\end{verbatim}
If at any point, you want to change your working directory to another folder, you can use \texttt{setwd()}. Different from \texttt{getwd()}, \texttt{setwd()} requires an argument within its brackets. To set a new working directory, you need to copy and paste the pathway within the brackets and in quotation marks ("").
This code is helpful when you need to pull files outside of the default working directory. However, you should be mindful when using this function because it gets very confusing very quickly.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\#setwd("")}
\end{Highlighting}
\end{Shaded}
Another important function is \texttt{dir()}. This function lets you check all of the files that exist in your working directory.
This function is a good option if you want to check if there are any extra or missing files from your working directory.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{dir}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "_book"
## [2] "_bookdown.yml"
## [3] "_bookdown_files"
## [4] "_build.sh"
## [5] "_deploy.sh"
## [6] "_output.yml"
## [7] "0-r-and-rstudio-set-up.Rmd"
## [8] "1-introduction-to-r.Rmd"
## [9] "2-importing-data-into-r-with-readr.Rmd"
## [10] "3-introduction-to-nhanes.Rmd"
## [11] "4-data-analysis-with-dplyr.Rmd"
## [12] "5-data-visualization-with-ggplot.Rmd"
## [13] "6-date-time-data-with-lubridate.Rmd"
## [14] "7-data-summary-with-tableone.Rmd"
## [15] "8-Exercise-Solutions.Rmd"
## [16] "9-references.Rmd"
## [17] "book.bib"
## [18] "data"
## [19] "DESCRIPTION"
## [20] "Dockerfile"
## [21] "docs"
## [22] "header.html"
## [23] "images"
## [24] "index.Rmd"
## [25] "intro2R.Rmd"
## [26] "intro2R_cache"
## [27] "intro2R_files"
## [28] "LICENSE"
## [29] "now.json"
## [30] "packages.bib"
## [31] "preamble.tex"
## [32] "R.Rproj"
## [33] "README.md"
## [34] "style.css"
## [35] "toc.css"
\end{verbatim}
You will see that there are 2 CSV files in our working directory: last\_15\_bpx.csv and last\_15\_demo.csv. Do not worry about what they are right now (we will cover this in later tutorials). All you have to know for now is that these two files are currently residing in our input/tutorial-demo folder, AKA our working directory.
The example above is only to demonstrate how we would change our working directory. But since we want to remain in our default working directory for the rest of this tutorial, we will set our working directory back to the original directory.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# setwd("..") \# this ".." argument allows us to move back 1 folder}
\CommentTok{\# setwd("..") }
\CommentTok{\# setwd("..") \# so doing this three times means that we are moving back 3 folders}
\CommentTok{\# setwd("./data/") }
\CommentTok{\# now we\textquotesingle{}re back in the large folder that houses both input/tutorial{-}demo and kaggle/working}
\end{Highlighting}
\end{Shaded}
After setting a new working directory, it is in our best interest to check the working directory again to see if we are in the right place.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# check to see if we\textquotesingle{}re back to our original directory}
\FunctionTok{getwd}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "C:/Users/ehsan/Documents/GitHub/intro2R"
\end{verbatim}
\hypertarget{functions-debunked}{%
\subsubsection{Functions Debunked}\label{functions-debunked}}
Throughout our tutorials, you will see a recurring section named \textbf{Functions Debunked}. These sections aim to break down the function that you were just introduced to. Each of these section will include a link for you to find more information about the function, the different arguments that can be nested within each function, and an example.
For this first section, we will debunk \texttt{\#}. When you see a \texttt{\#} in a code chunk, this means that the following information is a note or comment. In other words, it doesn't code for anything - it is just notes explaining what we are doing. You can try adding a \texttt{\#} in front of our \texttt{getwd()} code above to see what happens!
If this doesn't make any sense to you right now, do not worry! It will make more sense as we move along the tutorials.
\hypertarget{installing-and-attaching-packages}{%
\subsection{Installing and Attaching Packages}\label{installing-and-attaching-packages}}
Now that we understand what working directories are, we can move onto installing and attaching packages.
There are a lot of packages on R, each has its own set of functions for different purposes. To access each set of function, we need to install the respective package. To install a package, we use \texttt{install.packages()}. Within the brackets, the only argument you need is the name of the package in quotation marks ("").
The most basic package on R is Base R. We do not actually need to install this package as it should be built into R by default. Therefore, by default, we should already have access to a range of basic R functions without having to install any packages. In this tutorial, we will only be using functions in this Base R package. However, in future tutorials, we will need to install pacakages such as dplyr and ggplot, which will give you access to even more and more advanced functions.
For the sake of demonstration, the ggplot2 package is installed below, but note that we will not be using any ggplot functions in this tutorial.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# install.packages("ggplot2")}
\end{Highlighting}
\end{Shaded}
A related function is \texttt{library()}. This function is used to attach installed packages to your R session. Unlike \texttt{install.packages()} where you only need to use once, \texttt{library()} needs to be run every R session. In other words, you need to attach whatever package you need everytime to you and then reopen R.
In future tutorials, if the \texttt{library()} function does not work for you, it is most likely because you have not installed the package, and therefore need to use \texttt{install.packages()} first before \texttt{library()}.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# another difference from install.packages() is that we do not need "" in library()}
\FunctionTok{library}\NormalTok{(ggplot2)}
\end{Highlighting}
\end{Shaded}
To make sure the package is successfully attached, we can try running a function in that package. After running the code below, you should only see a blank square. This is correct! We will go over why this is in tutorial 5.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{ggplot}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\includegraphics{intro2R_files/figure-latex/unnamed-chunk-8-1.pdf}
\hypertarget{do-questions-1-3-of-the-google-quiz-now}{%
\subsubsection{DO QUESTIONS 1-3 OF THE GOOGLE QUIZ NOW}\label{do-questions-1-3-of-the-google-quiz-now}}
\begin{quote}
What is a ``Working Directory''?
\end{quote}
\begin{quote}
What is the main difference between \texttt{setwd()} and \texttt{getwd()}?
\end{quote}
\begin{quote}
We need to install the packages first before we can load them using \texttt{library()}. (True or False)
\end{quote}
\hypertarget{arithmetic-operators}{%
\section{2. ARITHMETIC OPERATORS}\label{arithmetic-operators}}
As expected from a data analysis software, you can use R like a calcultor using arithmetic operators! Here is a list of a few basic and common arithmetic operators in R:
\begin{figure}
\centering
\includegraphics{https://i.imgur.com/1ww25MM.png}
\caption{Figure 1. Arithmetic Operators in R}
\end{figure}
These operators will prove themselves to be more useful in data analysis when we get to later tutorials, especially our Tutorial 4 on the dplyr package.
\hypertarget{try-it-yourself}{%
\subsection{1.1 Try it yourself}\label{try-it-yourself}}
\begin{enumerate}
\def\labelenumi{\alph{enumi}.}
\tightlist
\item
Can you replicate and solve these problems in R?
\end{enumerate}
\begin{itemize}
\tightlist
\item
2\^{}2
\item
2 × 2
\item
2 + 5 × (5 ÷ 4)\^{}6
\item
what is the remainder of 52 ÷ 5
\item
what is the whole number solution to 82 ÷ 8
\end{itemize}
\begin{enumerate}
\def\labelenumi{\alph{enumi}.}
\setcounter{enumi}{1}
\tightlist
\item
Can you solve for x using R?
\end{enumerate}
a \textless- 9 + 3 * 6
x \textless- a ÷ 2
\hypertarget{do-question-4-of-the-quiz-now}{%
\subsubsection{DO QUESTION 4 OF THE QUIZ NOW}\label{do-question-4-of-the-quiz-now}}
\begin{quote}
The output of \texttt{10\ \%\%\ 2} is equal to which of the following?
\end{quote}
\hypertarget{logical-operators}{%
\section{3. LOGICAL OPERATORS}\label{logical-operators}}
In addition, logical operators are also available on R. The main difference between arithmetic operators and logical operators is that logical operators will yield a logical (or TRUE/FALSE) output. This is a list of some common logical operators that can be used on R:
\begin{figure}
\centering
\includegraphics{https://i.imgur.com/xG4F5kA.png}
\caption{Figure 2. Logical Operators in R}
\end{figure}
Similarly, these operators will be more useful when we learn about filtering data in future tutorials and you will also be provided with more examples then.
Here are a few example codes that you can try running:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\OtherTok{\textless{}{-}} \DecValTok{5} \SpecialCharTok{\textgreater{}} \DecValTok{4}
\CommentTok{\# the \textless{}{-} indicates that the information 5 \textgreater{} 4 is stored in the variable a {-} we will cover this in more detail in Section 4 of this tutorial}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{b }\OtherTok{\textless{}{-}} \DecValTok{8}
\NormalTok{b }\SpecialCharTok{!=} \DecValTok{8}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] FALSE
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{a }\SpecialCharTok{==}\NormalTok{ b}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] FALSE
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\DecValTok{9} \SpecialCharTok{+} \DecValTok{10} \SpecialCharTok{*} \DecValTok{15} \SpecialCharTok{{-}} \DecValTok{8} \SpecialCharTok{\textless{}=} \DecValTok{103}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] FALSE
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\DecValTok{11}\SpecialCharTok{+} \DecValTok{3}\SpecialCharTok{\^{}}\DecValTok{9} \SpecialCharTok{==} \DecValTok{19694}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] TRUE
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# note that in R, "equal to" is coded by ==, = has another meaning that you will see in section 4}
\end{Highlighting}
\end{Shaded}
\hypertarget{try-it-yourself-1}{%
\subsection{1.2 Try it yourself}\label{try-it-yourself-1}}
Translate the following into R and find the output:
* 8 times 3 is greater than 8?
* eleven divided by seven is not equal to 2?
* 9 is less than or equal to 18?
\hypertarget{do-question-5-of-the-quiz-now}{%
\subsubsection{DO QUESTION 5 OF THE QUIZ NOW}\label{do-question-5-of-the-quiz-now}}
\begin{quote}
Which of the following operators code for ``equal to''?
\end{quote}
\hypertarget{most-common-data-types-in-r}{%
\section{4. MOST COMMON DATA TYPES IN R}\label{most-common-data-types-in-r}}
\hypertarget{strings}{%
\subsection{Strings}\label{strings}}
Strings are either single character or a collection of characters. Note that all strings are in \texttt{""}. For example:
\begin{Shaded}
\begin{Highlighting}[]
\StringTok{"hello, my name is Alex"}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "hello, my name is Alex"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\StringTok{"Where are you?"}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "Where are you?"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\StringTok{"I like to eat 6 apples"}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "I like to eat 6 apples"
\end{verbatim}
\hypertarget{vectors}{%
\subsection{Vectors}\label{vectors}}
Vector is the simplest data type in R. It is basically a list of components stored in the same place (or variable). To write a vector, starts with \texttt{c()} and input the appropriate components within the brackets. For example:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{, }\DecValTok{2}\NormalTok{, }\DecValTok{3}\NormalTok{) }\CommentTok{\# numeric}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 1 2 3
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{c}\NormalTok{(}\StringTok{"hello"}\NormalTok{, }\StringTok{"bonjour"}\NormalTok{, }\StringTok{"ciao"}\NormalTok{) }\CommentTok{\# character – note that text needs to be in “”}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "hello" "bonjour" "ciao"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{) }\CommentTok{\# logical – we will cover this in more detail later}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] TRUE FALSE TRUE
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{, }\StringTok{"hello"}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{) }\CommentTok{\# mixed}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "1" "hello" "TRUE"
\end{verbatim}
We can also store these vectors using the symbol \texttt{\textless{}-}.
\textbf{Note:} If you are using RStudio, they will be stored in our environment located in the top right window.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{numeric }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{, }\DecValTok{2}\NormalTok{, }\DecValTok{3}\NormalTok{, }\DecValTok{10}\SpecialCharTok{:}\DecValTok{12}\NormalTok{) }\CommentTok{\# 10:12 means 10, 11, 12!}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{character }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"hello"}\NormalTok{, }\StringTok{"bonjour"}\NormalTok{, }\StringTok{"ciao"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{logical }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{TRUE}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
What we just did was assigning values to variables where numeric, character, and logical are all variables!
\hypertarget{try-it-yourself-2}{%
\subsection{1.3 Try it yourself}\label{try-it-yourself-2}}
Can you try storing a string? Assign the string ``hello world, I am here'' to the variable named start.
\textbf{Note how the string is in "" but the variable name is not. Why do you think this is?}
After assigning values to our variables, we can tell R to retrieve them by typing any of these variable names. R will give us the components of data that we assigned to each variable as the output.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{numeric}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 1 2 3 10 11 12
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{character}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "hello" "bonjour" "ciao"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{logical}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] TRUE FALSE TRUE
\end{verbatim}
If you want to extract a particular component from a variable, you can use \texttt{{[}{]}}. For example:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{numeric[}\DecValTok{1}\SpecialCharTok{:}\DecValTok{4}\NormalTok{] }\CommentTok{\# the first 4 components}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 1 2 3 10
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{character[}\DecValTok{2}\NormalTok{] }\CommentTok{\# only the 2nd component}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "bonjour"
\end{verbatim}
\hypertarget{try-it-yourself-3}{%
\subsection{1.4 Try it yourself}\label{try-it-yourself-3}}
It is important to note that \textbf{R is case-sensitive}. This means that it distinguishes capitalized from non-capitalized characters, so logical and Logical are read as two separate things by R!
Try typing Logical with a capitalized ``L''. How does R respond to this?
We can also replace \texttt{\textless{}-} with \texttt{=} when assigning values to variables. But \texttt{=} has other uses as well - you will be introduced to their slight differences in future tutorials. Also, note that in R, \texttt{=} does not mean ``equal to''. As you have see in the previous section, ``equal to'' is coded by \texttt{==}.
\hypertarget{lists}{%
\subsection{Lists}\label{lists}}
A list is a collection of possibly unrelated components. It allows you to gather different types of data into one place. In the code below, we have numbers, characters, and data frame all in one place.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{list }\OtherTok{\textless{}{-}} \FunctionTok{list}\NormalTok{(}\AttributeTok{numeric =} \DecValTok{1}\NormalTok{, }\AttributeTok{character =} \FunctionTok{c}\NormalTok{(}\StringTok{"bonjour"}\NormalTok{, }\StringTok{"hello"}\NormalTok{), }\StringTok{"I like to eat 6 apples"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Similarly, you can also extract specific information from this list using \texttt{{[}{]}}. Note that in the code below, the output is ``bonjour'' AND ``hello'', this is because the second component of our list is a vector that houses both of these words.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{list[}\DecValTok{2}\NormalTok{]}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## $character
## [1] "bonjour" "hello"
\end{verbatim}
\hypertarget{functions-debunked-1}{%
\subsubsection{Functions Debunked}\label{functions-debunked-1}}
The arguments for \href{https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/list}{list()} are as follows:
list(
\textgreater{} \textbf{VARIABLE NAME OF ANY DATA TYPE} = \textbf{ANY DATA STORED WITHIN THAT VARIABLE} OR \textbf{ANY STRING}
)
\textbf{For example:} \texttt{list(numeric\ =\ 1,\ character\ =\ c("bonjour",\ "hello"),\ dataframe\ =\ logical)}
\hypertarget{dataframe}{%
\subsection{Dataframe}\label{dataframe}}
Dataframe, you guessed it, stores your data in the form of a dataframe or a table! Dataframe allows you to store multiple vectors into one single table.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dataframe }\OtherTok{\textless{}{-}} \FunctionTok{data.frame}\NormalTok{(numeric, character, logical)}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dataframe}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## numeric character logical
## 1 1 hello TRUE
## 2 2 bonjour FALSE
## 3 3 ciao TRUE
## 4 10 hello TRUE
## 5 11 bonjour FALSE
## 6 12 ciao TRUE
\end{verbatim}
\hypertarget{functions-debunked-2}{%
\subsubsection{Functions debunked}\label{functions-debunked-2}}
The arguments for \href{https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/data.frame}{data.frame()} are as follows:
data.frame(
\textgreater{} \textbf{VECTOR 1}
\begin{quote}
\textbf{VECTOR 2}
\end{quote}
\begin{quote}
\textbf{VECTOR n}
\end{quote}
)
\textbf{For example:} \texttt{dataframe\ \textless{}-\ data.frame(numeric,\ character,\ logical)}
If you want to change the column names of your data frame, you can use the function \texttt{names()}.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{names}\NormalTok{(dataframe) }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"Number"}\NormalTok{, }\StringTok{"Text"}\NormalTok{, }\StringTok{"T/F"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Now if we check our data frame again, the new column names should appear.
\begin{Shaded}