-
Notifications
You must be signed in to change notification settings - Fork 12
/
_main.tex
18408 lines (15136 loc) · 689 KB
/
_main.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}
\PassOptionsToPackage{dvipsnames,svgnames*,x11names*}{xcolor}
%
\documentclass[
]{book}
\usepackage{lmodern}
\usepackage{amssymb,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
\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={Computational Thinking for Social Scientists},
pdfauthor={Jae Yeon Kim},
colorlinks=true,
linkcolor=Maroon,
filecolor=Maroon,
citecolor=Blue,
urlcolor=Blue,
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}
% 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}
\usepackage{amsthm}
\makeatletter
\def\thm@space@setup{%
\thm@preskip=8pt plus 2pt minus 4pt
\thm@postskip=\thm@preskip
}
\makeatother
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
\usepackage{xcolor}
\usepackage[]{natbib}
\bibliographystyle{apalike}
\title{Computational Thinking for Social Scientists}
\author{\href{https://jaeyk.github.io/}{Jae Yeon Kim}}
\date{2020-10-28}
\begin{document}
\maketitle
{
\hypersetup{linkcolor=}
\setcounter{tocdepth}{1}
\tableofcontents
}
\hypertarget{hello-world}{%
\chapter{Hello World}\label{hello-world}}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{print}\NormalTok{(}\StringTok{"Hello, World!"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "Hello, World!"
\end{verbatim}
\begin{quote}
Make simple things simple, and complex things possible. - \href{https://www.quora.com/What-is-the-story-behind-Alan-Kay-s-adage-Simple-things-should-be-simple-complex-things-should-be-possible}{Alan Kay}
\end{quote}
This is the website for \emph{Computational Thinking for Social Scientists}. This book intends to help social scientists to think computationally and develop proficiency with computational tools and techniques, necessary to conduct research in computational social science. Mastering these tools and techniques not only enables social scientists to collect, wrangle, analyze, and interpret data with less pain and more fun, but it also let them to work on research projects that would previously seem impossible.
The book is not intended to be a comprehensive guide for computational social science or any particular programming language, computational tool or technique. For general introduction to computational social science, I recommend \href{http://www.princeton.edu/~mjs3/}{Matthew Salganik}'s \href{https://www.bitbybitbook.com/}{Bit By Bit (2017)}.
The book is currently divided into two main subjects (fundamentals and applications) and seven main sessions.
\hypertarget{part-i-fundamentals}{%
\subsection{Part I Fundamentals}\label{part-i-fundamentals}}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
\protect\hyperlink{motivation}{Why computational thinking}
\item
\protect\hyperlink{git_bash}{Best practices in data and code management using Git and Bash}
\item
\protect\hyperlink{tidy_data}{How to wrangle, model, and visualize data easier and faster}
\item
\protect\hyperlink{functional_programming}{How to use functions to automate repeated things and develop data products (e.g., packages and apps)}
\end{enumerate}
\hypertarget{part-ii-applications}{%
\subsection{Part II Applications}\label{part-ii-applications}}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{4}
\item
\protect\hyperlink{semi_structured_data}{How to collect and parse semi-structured data at scale (e.g., using APIs and webscraping)}
\item
\protect\hyperlink{machine_learning}{How to analyze high-dimensional data (e.g., text) using machine learning}
\item
\protect\hyperlink{big_data}{How to access, query, and manage big data using SQL and Spark}
\end{enumerate}
The book teaches how to do all of these mostly in \href{https://www.r-project.org/about.html}{\textbf{R}}, and sometimes in \href{https://www.gnu.org/software/bash/}{\textbf{bash}} and \href{https://www.python.org/about/}{\textbf{Python}}.
\begin{itemize}
\item
Why R? R is free, easy to learn (thanks to \href{https://www.tidyverse.org/}{\texttt{tidyverse}} and \href{https://rstudio.com/}{RStudio}), fast (thanks to \href{https://cran.r-project.org/web/packages/Rcpp/index.html}{\texttt{Rcpp}}), runs everywhere, \textbf{open} (16,000+ packages; counting only ones \href{https://cran.r-project.org/web/packages/}{available at CRAN}), and has a growing massive and inclusive community (\href{https://twitter.com/search?q=\%23rstats\&src=typed_query}{\texttt{\#rstats}}).
\item
Why R + Python + bash?
\begin{quote}
\begin{quote}
``For R and Python, Python is first and foremost a programming language. And that has a lot of good features, but it tends to mean, that if you are going to do data science in Python, you have to first learn how to program in Python. Whereas I think you are going to get up and running faster with R, than with Python because there's just a bunch more stuff built in and you don't have to learn as many programming concepts. You can focus on being a great political scientist or whatever you do and learning enough R that you don't have to become an expert programmer as well to get stuff done.'' - Hadley Wickham
\end{quote}
\end{quote}
\begin{itemize}
\tightlist
\item
However, this feature of the R community also raises a challenge.
\end{itemize}
\begin{quote}
\begin{quote}
Compared to other programming languages, the R community tends to be more focused on results instead of processes. Knowledge of software engineering best practices is patchy: for instance, not enough R programmers use source code control or automated testing. Inconsistency is rife across contributed packages, even within base R. You are confronted with over 20 years of evolution every time you use R. R is not a particularly fast programming language, and poorly written R code can be terribly slow. R is also a profligate user of memory. - Hadley Wickham
\end{quote}
\end{quote}
\begin{itemize}
\tightlist
\item
RStudio, especially the tidyverse team, has made heroic efforts to amend the problems listed above. Readers you will learn these recent advances in the R ecosystem and how to complement R with Python and Bash.
\end{itemize}
\end{itemize}
\hypertarget{special-thanks}{%
\section{Special thanks}\label{special-thanks}}
This book is collected as much as it is authored. It is a remix version of \href{https://github.com/rochelleterman/PS239T}{PS239T}, a graduate-level computational methods course at UC Berkeley, originally developed by \href{http://rochelleterman.com/}{Rochelle Terman} then revised by \href{http://rachelbernhard.com/}{Rachel Bernhard}. I have taught PS239T as lead instructor in Spring 2019 and TA in Spring 2018 and will co-teach it in Spring 2020. Other teaching materials draw from the workshops I have created for \href{https://dlab.berkeley.edu/}{D-Lab} and \href{https://data.berkeley.edu/research/discovery-program-home}{Data Science Discovery Program} at UC Berkeley. I also have cited all the other references whenever I am aware of related books, articles, slides, blog posts, or YouTube video clips.
\hypertarget{suggestions-questions-or-comments}{%
\section{Suggestions, questions, or comments}\label{suggestions-questions-or-comments}}
Please feel free to \href{https://github.com/jaeyk/PS239T/issues}{create issues} if you find typos, errors, missing citations, etc via the GitHub repository associated with this book.
\hypertarget{license}{%
\section{License}\label{license}}
\includegraphics{https://i.creativecommons.org/l/by/4.0/88x31.png} This work is licensed under a \href{https://creativecommons.org/licenses/by/4.0/}{Creative Commons Attribution 4.0 International License}.
\hypertarget{motivation}{%
\chapter{Computational thinking}\label{motivation}}
\hypertarget{why-computational-thinking}{%
\section{Why computational thinking}\label{why-computational-thinking}}
\begin{itemize}
\item
If social scientists want to know how to work smart and not just hard, they need to take full advantage of the power of modern programming languages, and that power is \textbf{automation}.
\item
Let's think about the following two cases.
\begin{itemize}
\item
Case 1: Suppose a social scientist needs to collect data on civic organizations in the United States from websites, Internal Revenue Service reports, and social media posts. As the number of these organizations is large, the researcher could not collect a large volume of data from diverse sources, so they would hire undergraduates and distribute tasks among them. This is a typical data collection plan in social science research, and it is labor-intensive. Automation is not part of the game plan. Yet, it is critical for so many reasons. Because the process is costly, no one is likely to either replicate or update the data collection effort. Put differently, without making the process efficient, it is difficult for it to be reproducible and scalable.
\item
Case 2: An alternative is to write computer programs that collect such data automatically, parse them, and store them in interconnected databases. Additionally, someone may need to maintain and validate the quality of the data infrastructure. Nevertheless, this approach lowers the cost of the data collection process, thereby substantially increasing the \textbf{reproducibility} and \textbf{scalability} of the process. Furthermore, the researcher can document their code and publicly share it using their GitHub repository or even gather some of the functions they used and distribute them as open-source libraries.
\end{itemize}
\item
Programming is as valuable a skill as writing in social science research. The extent to which a researcher can automate the research process can determine its efficiency, reproducibility, and scalability.
\end{itemize}
\begin{quote}
Every modern statistical and data analysis problem needs code to solve it. You shouldn't learn just the basics of programming, spend some time gaining mastery. Improving your programming skills pays off because code is a \textbf{force multiplier}: once you've solved a problem once, code allows you to solve it much faster in the future. As your programming skill increases, the generality of your solutions improves: you solve not just the precise problem you encountered, but a wider class of related problems (in this way programming skill is very much like mathematical skill). Finally, sharing your code with others allows them to benefit from your experience. - \href{https://imstat.org/2014/12/16/hadley-wickham-impact-the-world-by-being-useful/}{Hadley Wickham}
\end{quote}
\begin{itemize}
\tightlist
\item
How can we automate our research process? How can we talk to and teach a machine?
\end{itemize}
\begin{figure}
\centering
\includegraphics{https://bam.files.bbci.co.uk/bam/live/content/znmb87h/large}
\caption{From BBC Bitesize}
\end{figure}
\begin{itemize}
\item
This book teaches how you to do that in R in incremental steps.
\begin{itemize}
\tightlist
\item
From graphic user interface to command-line interface
\item
From short programs to long programs
\item
The ultimate goal is to solve complex problems at scale using computation
\end{itemize}
\end{itemize}
\begin{quote}
``{[}W{]}e wanted users to be able to begin in an interactive environment, where they did not consciously think of themselves as progamming. Then as their needs became clearer and their sophistication increased, they should be able to slide gradually into programming, when the language and system aspects would become more important.'' - \emph{Stages in the Evolution of S} by John Chambers (S is the progenitor of R)
\end{quote}
\hypertarget{computational-way-of-thinking-about-data}{%
\section{Computational way of thinking about data}\label{computational-way-of-thinking-about-data}}
\hypertarget{structure}{%
\subsection{Structure}\label{structure}}
\begin{itemize}
\tightlist
\item
Structured data (Excel spreadsheets, CSVs)
\begin{itemize}
\tightlist
\item
Tidy data
\end{itemize}
\item
Semi-structured data
\begin{itemize}
\tightlist
\item
HTML/CSS: Websites
\item
JSON/XML: APIs
\end{itemize}
\end{itemize}
\hypertarget{dimension}{%
\subsection{Dimension}\label{dimension}}
\begin{itemize}
\item
n = the number of observations
\item
p = the number of variables
\item
Low-dimensional data (n \textgreater{} p)
\begin{itemize}
\tightlist
\item
Survey, experimental, and administrative data
\end{itemize}
\item
High-dimensional data (n \textless{} p)
\begin{itemize}
\tightlist
\item
Text, speech, image, video, etc.
\end{itemize}
\end{itemize}
\hypertarget{size}{%
\subsection{Size}\label{size}}
\begin{itemize}
\tightlist
\item
Data fit in your laptop's memory
\item
Data don't fit in your laptop's memory (=big data)
\end{itemize}
\hypertarget{computational-way-of-thinking-about-research-process}{%
\section{Computational way of thinking about research process}\label{computational-way-of-thinking-about-research-process}}
Computational tools and techniques make \ldots{}
\begin{itemize}
\tightlist
\item
Doing traditional research easier, faster, scalable, and more reproducible
\begin{itemize}
\tightlist
\item
Data wrangling
\item
Modeling
\item
Visualization
\end{itemize}
\item
Documentation and collaboration easier, faster and scalable
\begin{itemize}
\tightlist
\item
Dynamic reporting (markdown)
\item
Version control system (Git and GitHub)
\end{itemize}
\item
Collecting and analyzing large and complex data possible
\begin{itemize}
\tightlist
\item
Digital data collection (API and web scraping)
\begin{itemize}
\tightlist
\item
Building a data infrastructure (SQL)
\end{itemize}
\item
Machine learning
\end{itemize}
\end{itemize}
\hypertarget{git_bash}{%
\chapter{Managing data and code}\label{git_bash}}
\hypertarget{getting-started-in-r}{%
\section{Getting started in R}\label{getting-started-in-r}}
\hypertarget{rstudio}{%
\subsection{RStudio}\label{rstudio}}
There are two main ways of interacting with R: using the console or by using script files (plain text files that contain your code).
If R is ready to accept commands, the R console shows a \texttt{\textgreater{}} prompt. If it receives a command (by typing, copy-pasting or sent from the script editor using \texttt{Ctrl-Enter}; \texttt{Command-Enter} will also work on Macs), R will try to execute it, and when ready, show the results and come back with a new \texttt{\textgreater{}}-prompt to wait for new commands. This is the equivalent of the \texttt{\$} in your terminal.
\hypertarget{basic-syntax}{%
\subsection{Basic Syntax}\label{basic-syntax}}
\textbf{Comments}
Use \texttt{\#} signs to comment. Comment liberally in your R scripts. Anything to the right of a \texttt{\#} is ignored by R. For those of you familiar with other languages, there is no doc string, or equivalent to \texttt{"""} in R.
\textbf{Assignment operator}
\texttt{\textless{}-} is the assignment operator. It assigns values on the right to objects on the left. So, after executing \texttt{x\ \textless{}-\ 3}, the value of \texttt{x} is \texttt{3}. The arrow can be read as 3 \textbf{goes into} \texttt{x}. You can also use \texttt{=} for assignments.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{USweird \textless{}{-}}\StringTok{ "Why use lb for pound!"} \CommentTok{\# Use this}
\StringTok{"Why use lb for pound!"}\NormalTok{ =}\StringTok{ }\NormalTok{USweird}
\end{Highlighting}
\end{Shaded}
Nonetheless, \emph{can} does not mean you \emph{should}. It is good practice to use \texttt{\textless{}-} for assignments. \texttt{=} should only be used to specify the values of arguments of functions. This is what Google and Hadley Wickham recommend as well. If they don't convince you enough, here's \href{https://csgillespie.wordpress.com/2010/11/16/assignment-operators-in-r-vs/}{a real example}.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{mean}\NormalTok{(}\DataTypeTok{x =} \DecValTok{1}\OperatorTok{:}\DecValTok{10}\NormalTok{) }\CommentTok{\# Does it save x?}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 5.5
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{rm}\NormalTok{(x)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Warning in rm(x): object 'x' not found
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{mean}\NormalTok{(x \textless{}{-}}\StringTok{ }\DecValTok{1}\OperatorTok{:}\DecValTok{10}\NormalTok{) }\CommentTok{\# Does it save x?}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 5.5
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{rm}\NormalTok{(x)}
\end{Highlighting}
\end{Shaded}
\textbf{Printing}
In R, the contents of an object can be printed by either simply executing the the object name or calling the \texttt{print()} function.
\textbf{Help}
\begin{itemize}
\tightlist
\item
\texttt{?} + object opens a help page for that specific object
\item
\texttt{??} + object searches help pages containing the name of the object
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{?mean}
\NormalTok{??mean}
\KeywordTok{help}\NormalTok{(mean)}
\CommentTok{\# The above three will do same. }
\KeywordTok{example}\NormalTok{(ls) }\CommentTok{\# provides example for how to use ls }
\KeywordTok{help.search}\NormalTok{(}\StringTok{"visualization"}\NormalTok{) }\CommentTok{\# search functions and packages that have "visualization" in their descriptions}
\end{Highlighting}
\end{Shaded}
\hypertarget{environment}{%
\section{Environment}\label{environment}}
Environment = a collection of pairs
\hypertarget{objects}{%
\subsection{Objects}\label{objects}}
\begin{itemize}
\tightlist
\item
List objects in your current environment
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Create a numeric object }
\NormalTok{x \textless{}{-}}\StringTok{ }\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{2}\NormalTok{,}\DecValTok{3}\NormalTok{,}\DecValTok{4}\NormalTok{,}\DecValTok{5}\NormalTok{)}
\CommentTok{\# List the object }
\KeywordTok{ls}\NormalTok{()}
\CommentTok{\# Remove the object }
\KeywordTok{rm}\NormalTok{(x)}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Remove objects from your current environment
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Create an object }
\NormalTok{x \textless{}{-}}\StringTok{ }\DecValTok{5}
\CommentTok{\# Remove the object }
\KeywordTok{rm}\NormalTok{(x)}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Remove all objects from your current environment
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Create an object }
\NormalTok{a \textless{}{-}}\StringTok{ }\DecValTok{7}
\NormalTok{b \textless{}{-}}\StringTok{ }\DecValTok{3}
\CommentTok{\# Remove the object }
\KeywordTok{rm}\NormalTok{(}\DataTypeTok{list =} \KeywordTok{ls}\NormalTok{())}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Force memory release
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Garbage collect; for more information, type ?gc() }
\KeywordTok{gc}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\hypertarget{packages}{%
\subsection{Packages}\label{packages}}
\texttt{install.packages(package-name)} will download a package from one of the CRAN mirrors assuming that a binary is available for your operating system.
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# From CRAN}
\KeywordTok{install.packages}\NormalTok{(}\StringTok{"dplyr"}\NormalTok{) }
\CommentTok{\# Load package }
\KeywordTok{library}\NormalTok{(dplyr)}
\CommentTok{\# From GitHub }
\NormalTok{devtools}\OperatorTok{::}\KeywordTok{install\_github}\NormalTok{(}\StringTok{"jaeyk/tidytweetjson"}\NormalTok{) }\CommentTok{\# my own package }
\CommentTok{\# Unload package }
\CommentTok{\# detach("package:stats", unload=TRUE)}
\end{Highlighting}
\end{Shaded}
\textbf{Tips}
If you have multiple packages to install, then please consider using pacman package. The following is the example. First, you install pacman. Then, you load several libraries by using \texttt{p\_load()} method.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{install.packages}\NormalTok{(}\StringTok{"pacman"}\NormalTok{)}
\NormalTok{pacman}\OperatorTok{::}\KeywordTok{p\_load}\NormalTok{(}
\NormalTok{ ggplot2,}
\NormalTok{ dplyr, }
\NormalTok{ broom}
\NormalTok{)}
\end{Highlighting}
\end{Shaded}
If you don't like to use \texttt{pacman}, then the other option is to create a list (we're going to learn what is list soon).
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{pkgs \textless{}{-}}\StringTok{ }\KeywordTok{c}\NormalTok{(}\StringTok{"ggplot2"}\NormalTok{, }\StringTok{"dplyr"}\NormalTok{, }\StringTok{"broom"}\NormalTok{)}
\KeywordTok{install.packages}\NormalTok{(pkgs)}
\end{Highlighting}
\end{Shaded}
Still, we have to write two lines. The simpler, the better, right? Here's another approach that can simplify the code further.
Note that \texttt{lapply()} applies (there's a family of apply functions) a function to a list. In this case, library to pkgs. apply is an advanced concept, which is related to anonymous functions. We will learn about it later when we study functions.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{inst \textless{}{-}}\StringTok{ }\KeywordTok{lapply}\NormalTok{(pkgs, library, }
\DataTypeTok{character.only =} \OtherTok{TRUE}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\hypertarget{project-oriented-research}{%
\section{Project-oriented research}\label{project-oriented-research}}
\hypertarget{computational-reproducibility}{%
\subsection{Computational reproducibility}\label{computational-reproducibility}}
\begin{itemize}
\item
Replication = code + data
\item
Computational reproduciblity = code + data + environment + distribution
\item
Reproducibility checklist by \href{http://www.biostat.jhsph.edu/~rpeng/}{Roger Peng}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
Start with science (avoid vague questions and concepts)
\item
Don't do things by hand (not only about automation but also documentation)
\item
Don't point and click (same problem)
\item
Teach a computer (automation also solves documentation to some extent)
\item
Use some version control
\item
Don't save output (instead keep the input and code)
\item
Set your seed
\item
Think about the entire pipeline
\end{enumerate}
\end{itemize}
\hypertarget{setup}{%
\subsubsection{Setup}\label{setup}}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{pacman}\OperatorTok{::}\KeywordTok{p\_load}\NormalTok{(}
\NormalTok{ tidyverse, }\CommentTok{\# tidyverse}
\NormalTok{ here }\CommentTok{\# computational reproducibility}
\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\hypertarget{motivation-1}{%
\subsubsection{Motivation}\label{motivation-1}}
Why do you need to make your research project computationally reproducible?
For your self-interest and public benefits.
\includegraphics{https://github.com/dlab-berkeley/efficient-reproducible-project-management-in-R/blob/master/misc/screenshot.png?raw=true}
\hypertarget{how-to-organize-files-in-a-project}{%
\subsubsection{How to organize files in a project}\label{how-to-organize-files-in-a-project}}
You won't be able to reproduce your project unless it is efficiently organized.
Step 1. \href{https://environments.rstudio.com/}{\textbf{Environment}} is part of your project. If someone can't reproduce your environment, they won't be able to run your code.
\begin{itemize}
\tightlist
\item
Launch R Studio. Choose Tools \textgreater{} Global Options. You should not check \texttt{Restor\ .RData\ into\ workspace\ at\ startup} and set saving workspace option to \texttt{NEVER}.
\end{itemize}
Step 2. For each project, create a project directory named after the project.
name\_of\_the\_project
\begin{itemize}
\tightlist
\item
data:
\begin{itemize}
\tightlist
\item
raw
\item
processed (all processed, cleaned, and tided)
\end{itemize}
\item
figures
\item
packrat (optional)
\item
reports (PDF, HTML, TEX, etc.,)
\item
results (model outcomes, etc.,)
\item
scripts (i.e., functions)
\item
.gitignore (for Git)
\item
name\_of\_project.Rproj (for R)
\item
README.md (for Git)
\end{itemize}
\begin{figure}
\centering
\includegraphics{https://datacarpentry.org/R-ecology-lesson/img/working-directory-structure.png}
\caption{Working directory structure example}
\end{figure}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Don\textquotesingle{}t name it a project. Use a name that\textquotesingle{}s more informative. For instance, us\_election not my\_project.}
\KeywordTok{dir.create}\NormalTok{(}\StringTok{"../us\_election"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Step 3. Launch R Studio. Choose File \textgreater{} New project \textgreater{} Browse existing directories \textgreater{} Create project This allows each project has its own workspace.
Step 4. Organize files by putting them in separate subdirectories and naming them in a sensible way.
\begin{itemize}
\item
Treat raw data as read only (raw data should be RAW!) and put in the \texttt{data} subdirectory.
\begin{itemize}
\tightlist
\item
Note that version control does not need replace backup. You still need to backup your raw data.
\end{itemize}
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{dir.create}\NormalTok{(here}\OperatorTok{::}\KeywordTok{here}\NormalTok{(}\StringTok{"us\_election"}\NormalTok{, }\StringTok{"data"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Separate read-only data from processed data and put in the \texttt{processed\_data} subdirectory.
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{dir.create}\NormalTok{(here}\OperatorTok{::}\KeywordTok{here}\NormalTok{(}\StringTok{"us\_election"}\NormalTok{, }\StringTok{"processed\_data"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Put your code in the \texttt{src} subdirectory.
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{dir.create}\NormalTok{(here}\OperatorTok{::}\KeywordTok{here}\NormalTok{(}\StringTok{"us\_election"}\NormalTok{, }\StringTok{"src"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Put generated outputs (e.g., tables, figures) in the \texttt{outputs} subdirectory and treat them as disposable.
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{dir.create}\NormalTok{(here}\OperatorTok{::}\KeywordTok{here}\NormalTok{(}\StringTok{"us\_election"}\NormalTok{, }\StringTok{"outputs"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Put your custom functions in the \texttt{functions} subdirectory. You can gather some of these functions and distribute them as an open-source library.
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{dir.create}\NormalTok{(here}\OperatorTok{::}\KeywordTok{here}\NormalTok{(}\StringTok{"us\_election"}\NormalTok{, }\StringTok{"src"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\textbf{Challenge}
Set a project structure for a project named ``starwars''.
\hypertarget{how-to-organize-code-in-a-r-markdown-file}{%
\subsubsection{How to organize code in a R markdown file}\label{how-to-organize-code-in-a-r-markdown-file}}
\begin{itemize}
\item
In addition to environment, \textbf{workflow} is an important component of project efficiency and reproducibility.
\item
What is R markdown? An R package, developed by \href{https://yihui.org/en/}{Yihui Xie}, that provides an authoring framework for data science. Xie is also a developer of many widely popular R packages such as \texttt{knitr}, \href{https://github.com/yihui/xaringan}{\texttt{xaringan}} (cool kids use xaringan not \href{https://en.wikipedia.org/wiki/Beamer_(LaTeX)}{Beamer} these days), \texttt{blogdown} (used to create \href{https://jaeyk.github.io/}{my personal website}), and \texttt{bookdown} (used to create this book) among many others.
\begin{itemize}
\tightlist
\item
Many applications: \href{https://rstudio.github.io/distill/basics.html}{reports}, \href{https://bookdown.org/yihui/rmarkdown/xaringan.html}{presentations}, \href{https://rmarkdown.rstudio.com/flexdashboard/}{dashboards}, \href{https://bookdown.org/yihui/rmarkdown/websites.html}{websites}\\
\item
Check out \href{https://ysc-rmarkdown.netlify.app/}{Communicating with R markdown workshop} by \href{https://alison.rbind.io/}{Alison Hill} (RStudio)
\begin{itemize}
\tightlist
\item
Alison Hill is a co-author of \href{https://bookdown.org/yihui/blogdown/}{\texttt{blogdown:\ Creating\ Websites\ with\ R\ Markdown.}}
\end{itemize}
\item
Key strengths: dynamic reporting + reproducible science + easy deployment
\end{itemize}
\end{itemize}
\begin{itemize}
\tightlist
\item
R Markdown basic syntax
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Header 1}
\CommentTok{\#\# Header 2}
\CommentTok{\#\#\# Header 3}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Use these section headers to indicate workflow.
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Import packages and data}
\CommentTok{\# Tidy data}
\CommentTok{\# Wrangle data}
\CommentTok{\# Model data}
\CommentTok{\# Visualize data}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\item
Press \texttt{ctrl\ +\ shift\ +\ o}. You can see a document outline based on these headers. This is a nice feature for finding code you need to focus.
\item
If your project's scale is large, then divide these sections into files, number, and save them in \texttt{code} subdirectory.
\begin{itemize}
\tightlist
\item
01\_wrangling.Rmd
\item
02\_modeling.Rmd
\ldots{}
\end{itemize}
\end{itemize}
\hypertarget{making-a-project-computationally-reproducible}{%
\subsubsection{Making a project computationally reproducible}\label{making-a-project-computationally-reproducible}}
\begin{itemize}
\item
\texttt{setwd()}: set a working directory.
\item
Note that using \texttt{setwd()} is not a reproducible way to set up your project. For instance, none will be able to run the following code except me.
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Set a working directory }
\KeywordTok{setwd}\NormalTok{(}\StringTok{"/home/jae/starwars"}\NormalTok{)}
\CommentTok{\# Do something }
\KeywordTok{ggplot}\NormalTok{(mtcars, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ mpg, }\DataTypeTok{y =}\NormalTok{ wt)) }\OperatorTok{+}
\StringTok{ }\KeywordTok{geom\_point}\NormalTok{()}
\CommentTok{\# Export the object. }
\CommentTok{\# dot means the working directory set by setwd()}
\KeywordTok{ggsave}\NormalTok{(}\StringTok{"./outputs/example.png"}\NormalTok{) }\CommentTok{\# This is called relative path }
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\item
Instead, learn how to use \texttt{here()}'.
\begin{itemize}
\item
Key idea: separate workflow (e.g., workspace information) from products (code and data). For more information, read Jenny Bryan's wonderful piece on \href{https://www.tidyverse.org/blog/2017/12/workflow-vs-script/}{project-oriented workflow}.
\item
Example
\end{itemize}
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# New: Reproducible }
\KeywordTok{ggplot}\NormalTok{(mtcars, }\KeywordTok{aes}\NormalTok{(}\DataTypeTok{x =}\NormalTok{ mpg, }\DataTypeTok{y =}\NormalTok{ wt)) }\OperatorTok{+}
\StringTok{ }\KeywordTok{geom\_point}\NormalTok{()}
\KeywordTok{ggsave}\NormalTok{(}\KeywordTok{here}\NormalTok{(}\StringTok{"project"}\NormalTok{, }\StringTok{"outputs"}\NormalTok{, }\StringTok{"example.png"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
How \texttt{here} works
\end{itemize}
\texttt{here()} function shows what's the top-level project directory.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{here}\OperatorTok{::}\KeywordTok{here}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\tightlist
\item
Build a path including subdirectories
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{here}\OperatorTok{::}\KeywordTok{here}\NormalTok{(}\StringTok{"project"}\NormalTok{, }\StringTok{"outputs"}\NormalTok{)}
\CommentTok{\#depth 1 \#depth 2}
\end{Highlighting}
\end{Shaded}
\begin{itemize}
\item
How \texttt{here} defines the top-level project directory. The following list came from \href{https://github.com/jennybc/here_here}{the here package vignette}).
\begin{itemize}
\item
Is a file named .here present?
\item
Is this an RStudio Project? (\textbf{Note that we already set up an RStudio Project!} So, if you use RStudio's project feature, then you are ready to use \texttt{here}.)
\item
Is this an R package? Does it have a DESCRIPTION file?
\item