-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcrime_mapping_textbook.tex
More file actions
2532 lines (1841 loc) · 170 KB
/
Copy pathcrime_mapping_textbook.tex
File metadata and controls
2532 lines (1841 loc) · 170 KB
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={Crime Mapping in R},
pdfauthor={Reka Solymosi and Juanjo Medina},
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}
\usepackage{booktabs}
\usepackage{amsthm}
\makeatletter
\def\thm@space@setup{%
\thm@preskip=8pt plus 2pt minus 4pt
\thm@postskip=\thm@preskip
}
\makeatother
\ifluatex
\usepackage{selnolig} % disable illegal ligatures
\fi
\usepackage[]{natbib}
\bibliographystyle{apalike}
\title{Crime Mapping in R}
\author{Reka Solymosi and Juanjo Medina}
\date{2021-02-03}
\begin{document}
\maketitle
{
\setcounter{tocdepth}{1}
\tableofcontents
}
\hypertarget{prelude}{%
\chapter*{Prelude}\label{prelude}}
\addcontentsline{toc}{chapter}{Prelude}
\hypertarget{introduction}{%
\section{Introduction}\label{introduction}}
This workbook contains the lab materials for our Crime Mapping module in Department of Criminology at the University of Manchester. This module is an optional unit open to 3rd year undergraduate and postgraduate students.
It makes use of R, as it is a free, open source tool, that has tremendous community support, and great versatility in mapping applications. You can find more details about the advantages of R for geospatial work \href{https://geocompr.robinlovelace.net/intro.html}{here}
Crime Mapping introduces students to the concepts of spatial data analysis. The aim is to familiarise students with basic concepts of GIS, and get acquainted with spatial statistics to be able to talk about data about crime, policing, and criminal justice topics situated in the places they occur. Details can be found in the Syllabus.
\hypertarget{disclaimer}{%
\section{Disclaimer}\label{disclaimer}}
Please beware that:
\begin{itemize}
\tightlist
\item
In making these notes, while we briefly cover some concepts, students are expected to do the weekly reading, and attend the weekly lectures, as well as participate in lab disucssions to receive a complete course experience. These notes are \emph{not} intended to be a stand-alone reference or textbook, rather a set of exercises to gain hands-on practice with the concepts introduced during the course.
\item
These pages are the content of the university course mentioned above. They are meant to (very gently) introduce students to the concept of spatial data analysis, and cover descriptive statsitics and the key concepts required to build an understanding of quantitative data analysis in crime research.
\item
The handouts below use, among other data sets, dara from the UK data service such as the Crime Survey for England and Wales that is available under a Open Government Licence. This dataset is designed to be a learning resource and should not be used for research purposes or the production of summary statistics.
\end{itemize}
\hypertarget{a-first-lesson-about-r}{%
\chapter{A first lesson about R}\label{a-first-lesson-about-r}}
In this lesson, you will be introduced to the programming language, \texttt{R}. After installing the related software and getting a basic idea of the R Studio interface, you will learn three \texttt{R} basics: operators, objects, and packages.
Unlike other statistical software like SPSS and STATA, \texttt{R} is a free, open-source software for performing statistical analysis and data visualization. In addition, \texttt{R} offers more analytical solutions, flexibility, and customization than these commonly used statistical software, and its popularity has increased substantially over the years.
We learn \texttt{R} because we hope that this is an important tool that you will continue to use in future. As it is free and has a community feel to it where anyone can create and upload new techniques, the idea is that you can use \texttt{R} long after this course. Even if data analysis is not in the future for you, learning how to conduct and interpret statistical output is a good skill to have -- much of our knowledge of the world includes statistics, so understanding the numbers and how they were derived are advantages. \texttt{R} uses a language called \textbf{object-oriented programming}, and though it may seem daunting at first, practice makes familiarity. Also, you can impress your friends with all your coding.
\hypertarget{install-r-r-studio}{%
\section{Install R \& R Studio}\label{install-r-r-studio}}
As \texttt{R} and \texttt{R\ Studio} are free software, you should be able to install these on your own machines at home. You may be working with different IT, so there are different options to allow a successful install. Our first activity will be to decide what approach to working with \texttt{R} and \texttt{R\ Studio} will be best for you.
\hypertarget{activity-1-identifying-your-operating-system}{%
\subsection{Activity 1: Identifying your operating system}\label{activity-1-identifying-your-operating-system}}
In this activity, you need to answer a question about your computer/IT that you will be working with for this class. That question is:
\begin{itemize}
\item
\textbf{What is your operating system}? Operating system refers to the software that your computer is running to deliver the basic functions. You may have, for example:
\begin{itemize}
\tightlist
\item
\emph{Windows or Linux} - if you have these, you are most likely going to have an easy time installing \texttt{R} and \texttt{R\ Studio}, so you should give the installation instructions below a try
\item
\emph{Apple} - if you have a Mac, there are some extra steps to install \texttt{R} and \texttt{R\ Studio}. Specifically, there will be an additional programme to download called Xcode, and additional steps to take.\\
\item
\emph{Chromebook} - Installing \texttt{R} and \texttt{R\ Studio} on a Chromebook involves installing Linux. Like with a Mac, there are some additional steps you will need to take, and some patience.
\end{itemize}
\end{itemize}
In your group google sheets, write down which operating system you have. This will guide which directions to follow later.
\hypertarget{activity-2-install-r-r-studio}{%
\subsection{Activity 2: Install R \& R Studio}\label{activity-2-install-r-r-studio}}
\hypertarget{some-notes-specific-to-your-operating-system.}{%
\subsubsection{Some notes specific to your operating system.}\label{some-notes-specific-to-your-operating-system.}}
Before you move on to the installation steps, look at your answer from Activity 1, and read or watch the advice specific to your operating system:
\begin{itemize}
\tightlist
\item
Windows: click \href{https://www.youtube.com/watch?v=VLWaED9jTiA}{here} for instructions
\item
Chromebook: read the tutorial \href{https://blog.sellorm.com/2018/12/20/installing-r-and-rstudio-on-a-chromebook/}{here}
\item
Mac, follow the guidance in the video \href{https://www.youtube.com/watch?v=cX532N_XLIs\&list=PLqzoL9-eJTNDw71zWePXyHx3_cm_fMP8S}{here} and then, you will also need to install command line tools, for that you can watch another video \href{https://www.youtube.com/watch?v=3Yd9J_dhSfY}{here}
\item
Linux: for ubuntu see the video \href{https://www.youtube.com/watch?v=kF0-FH-xBiE}{here} and if you have questions, let the teaching team know!
\end{itemize}
Once you have watched or read the instructions for your relevant operating system, you are now ready to actually have a go at downloading the software for yourself. Before you start, write in the google doc any questions or concerns, and once ready, install!
\hypertarget{install-r}{%
\subsubsection*{\texorpdfstring{Install \texttt{R}:}{Install R:}}\label{install-r}}
\addcontentsline{toc}{subsubsection}{Install \texttt{R}:}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
Go to \url{https://www.r-project.org/}
\item
Click the \href{https://cran.r-project.org/mirrors.html}{download R} link under the \emph{Getting Started} heading
\item
You will be asked to select a Comprehensive R Archive Network (CRAN) mirror. Click the URL closest to your location
\item
Click whichever download link is appropriate for your operating system (see above).
\item
Then click the \emph{install R for the first-time} link and proceed to install \texttt{R}
\end{enumerate}
\hypertarget{install-r-studio}{%
\subsubsection*{Install R Studio:}\label{install-r-studio}}
\addcontentsline{toc}{subsubsection}{Install R Studio:}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
Go to \url{https://rstudio.com/}
\item
Click the \emph{Download} link
\item
Scroll down and then click the DOWNLOAD button for the free version of
\texttt{RStudio}
\item
You will be taken to a website to download the free version of \texttt{RStudio} that is appropriate for your computer. Download and then install it.
\end{enumerate}
\hypertarget{plan-b-accessing-r-studio-remotely-throught-a-web-browser}{%
\subsubsection{Plan B: accessing R Studio remotely throught a web browser}\label{plan-b-accessing-r-studio-remotely-throught-a-web-browser}}
It might be that the above does not work and you find that there are some issues specific to your computer, or something just is not working. In that case, you have two options:
\begin{itemize}
\item
\emph{Option 1:} You can remotely access one of the university PCs from your browser (Firefox, Chrome, Safari, etc). You can find instructions how to do this \href{https://www.itservices.manchester.ac.uk/students/pc-on-campus/remote-cluster-access/}{here} , and the university IT helpdesk can help you access this too. If you do this, you will be able to use the version of \texttt{RStudio} installed in the computer clusters.
\item
\emph{Option 2}: You can access an online version of \texttt{R\ Studio}, which you can access through any web browser (Firefox, Chrome, Safari, etc). To do this, you visit \url{https://rstudio.cloud/}, click on `get started for free', choose the free account, and click on `sign up'. Then you can always visit this website and log in to use \texttt{R\ Studio} in the cloud. Note that you should start a \texttt{New\ Project} and name it \emph{Modelling Crime Data}, and then all your work will be saved in this project.
\end{itemize}
\hypertarget{open-up-and-explore-rstudio}{%
\section{Open up and explore RStudio}\label{open-up-and-explore-rstudio}}
In this session we will focus in developing basic familiarity with R Studio. You can use R without using R Studio, but R Studio is an app that makes it easier to work with R.
R Studio is what we call an IDE, an \textbf{integrated development environment}. It is a fancy way of saying that it is a cool interface designed to write programming code. Every time you open up R Studio you are in fact starting a R session. R Studio automatically runs R in the background. We will be interacting with R in this course unit via R Studio.
\includegraphics{img/rstudio.png}
When you first open R Studio, you will see (as in the image above) that there are 3 main windows. The bigger one to your left is the console. If you read the text in the console you will see that R Studio is indeed opening R and you can see what version of R you are running. Since R is constantly being updated the version you installed is likely more recent that the one we used at time of writing.
\hypertarget{activity-3-opening-up-the-script-pane}{%
\subsubsection{Activity 3: Opening up the script pane}\label{activity-3-opening-up-the-script-pane}}
The view in R Studio is structured so that you have 4 open windows in a regular session. However when you first open, you might be starting with only 3. To open the script pane (the one missing) click in the \emph{File} drop down Menu, select \emph{New File}, then \emph{R Script}.
\includegraphics{img/openscript.png}
You will now see the 4 window areas in display. On each of these areas you can shift between different views and panels. You can also use your mouse to re-size the different windows if that is convenient.
\includegraphics{img/the4views.png}
\hypertarget{the-four-panes-of-r-studio}{%
\subsection{The four panes of R Studio}\label{the-four-panes-of-r-studio}}
The purposes of the four panes in Figure above are the following:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
\textbf{Script and data view}: where you type your programming code that tells \texttt{R} what you want to do. These are essentially instructions that you type and save as a \textbf{script}, so that you can return to it later to remember what you did and to share it with others so that they can reproduce what you did.
\item
\textbf{Environment and history view}:
\end{enumerate}
\begin{enumerate}
\def\labelenumi{\roman{enumi})}
\item
\emph{2.1 Environment} tab- gives you the names of all the (data) objects that you have defined during your current \texttt{R} session, including number of observations and rows in those objects. We learn more about objects later.
\item
\emph{2.2 History} tab- shows you a history of all the code you have previously evaluated in the main console. One of the key advantages of doing data analysis this way - with code versus with a point and click interface like Excel or ArcGIS is that you are producing a written record of every step you take in the analysis. First time around it will take you time to write these instructions, it may be slower than pointing and clicking. And unlike with pointing and clicking you need to know the ``words'' and ``grammar'' of this language.
\end{enumerate}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{2}
\item
\textbf{Main console}: this is considered \texttt{R\textquotesingle{}s} heart, and it is where \texttt{R} evaluates the codes that you run. You can type your codes directly in the console, but for the sake of good habits, type them in the script and data view so you can save a record of them. Only type and run code from here if you want to debug or do some quick analysis.
\item
\textbf{File directory, Plots, Packages, Help}:
\end{enumerate}
\begin{enumerate}
\def\labelenumi{\roman{enumi})}
\item
\emph{4.1 Files} tab- allows you to see the files in the folder that is currently set as your working directory.
\item
\emph{4.2 Plots} tab- you will see any data visualizations that you produce here. You have not produced any yet, so it is empty now.
\item
\emph{4.3 Packages} tab- you will see the packages that are currently available to install. We will explain what these are soon, but know that they are an essential feature when working with \texttt{R}.
\item
\emph{4.4 Help} tab- you can access further information on the various packages.
\end{enumerate}
\hypertarget{activity-4-interacting-with-the-4-panes}{%
\subsubsection{Activity 4: Interacting with the 4 panes}\label{activity-4-interacting-with-the-4-panes}}
In the previous activity, you opened up the `script' pane. We now write some code in it, and see what happens.
To do this, go to your open version of \texttt{R\ Studio}, and type in the script pane the following:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{print}\NormalTok{(}\StringTok{"Hello world!"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
When you have typed this, you will have typed your first bit of code. Yet nothing is happening? That is because you also have to \textbf{RUN} the code.
You can do this by highlighting the code you wish to run, and clicking on `run' in the top right hand corner:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{knitr}\SpecialCharTok{::}\FunctionTok{include\_graphics}\NormalTok{(}\StringTok{\textquotesingle{}img/run\_hello\_world.gif\textquotesingle{}}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\includegraphics[width=400px]{img/run_hello_world}
When you `run' the code, it will print the text `Hello World!' in the bottom pane, which is the \textbf{console}. That means you have written and executed your first line of code.
In the rest of the session, we will be unpacking how this all works, and getting more familiar and comfortable with using \texttt{R\ Studio}.
To recap: the \textbf{script} is where you write your programming code. A script is nothing but a text file with some code on it. Unlike other programs for data analysis you may have used in the past (Excel, SPSS), you need to interact with R by means of writing down instructions and asking R to evaluate those instructions. R is an \emph{interpreted} programming language: you write instructions (code) that the R engine has to interpret in order to do something. And all the instructions we write can and should be saved in a script, so that you can return later to what you did.
One of the key advantages of doing spatial data analysis this way - with code versus with a point and click interface like ArcGIS or MapInfo (or even QGIS) is that you are producing a written record of every step you take in the analysis. First time around it will take you time to write these instructions, it may be slower than pointing and clicking. And unlike with pointing and clicking you need to know the ``words'' and ``grammar'' of this language.
The advantage of doing analysis this way is that once you have written your instructions and saved them in a file, you will be able to share it with others and run it every time you want in a matter of seconds. This creates a \emph{reproducible} record of your analysis: something that your collaborators or someone else anywhere (including your future self, the one that will have forgotten how to do the stuff) could run and get the same results than you did at some point earlier. This makes science more transparent and transparency brings with it many advantages. For example, it makes your research more trustworthy. Don't underestimate how critical this is. \textbf{Reproducibility} is becoming a key criteria to assess good quality research. The University of Manchester \href{https://www.staffnet.manchester.ac.uk/news/display/?id=25496}{just joined the UK Reproducibility Network}, and is promoting this good practice. If you're interested you can join \href{https://research-it.manchester.ac.uk/news/2019/05/30/uom-open-science-working-group/}{the Open Science working group} or the reading club \href{https://reproducibilitea.org/journal-clubs/\#Manchester}{ReproducibiliTea}. You can read up on reproducibility and its importance \href{http://theconversation.com/the-science-reproducibility-crisis-and-what-can-be-done-about-it-74198}{here} or get Stuart Richie's book \href{https://www.goodreads.com/book/show/52199285-science-fictions}{Science Fictions} for an engaging further read.
\hypertarget{customising-the-rstudio-look}{%
\section{Customising the RStudio look}\label{customising-the-rstudio-look}}
R Studio allows you to customise the way it looks. Working with white backgrounds is not generally a good idea if you care about your eyesight. If you don't want to end up with dry eyes not only it is good you follow the 20-20-20 rule (every 20 minutes look for 20 seconds to an object located 20 feet away from you), but it may also be a good idea to use more eye friendly screen displays.
Click in the \emph{Tools} menu and select \emph{Global options}. This will open up a pop up window with various options. Select \emph{Appearance}. In this section you can change the font type and size, but also the kind of theme background that R will use in the various windows.
\includegraphics{img/tools_global_options.png}
You can make any changes you'd like to here, including the theme background that \texttt{R} will use as the interface.
For example, you may choose a darker theme like `tomorrow night bright'.
\includegraphics{img/appearance_choose_tomorrow_night_bright.png}
\includegraphics{img/consoleresults.png}
As indicated above, the window in the bottom left corner is the main \textbf{console}.You will see that the words ``I love maps'' appear printed there. If rather than using R Studio you were working directly from R, that's all you would get: the main console where you can write code interactively (rather than all the different windows you see in R Studio). You can write your code directly in the main console and execute it line by line in an interactive fashion. However, we will be running code from scripts, so that you get used to the idea of properly documenting all the steps you take,
\hypertarget{functions}{%
\subsection{Functions}\label{functions}}
\textbf{Functions} \emph{do} things. They are called by a certain name, usually a name which represents what they do, and they are followed by brackets \texttt{()}. Within the brackets, you can put whatever it is that you want the function to work with. For example, the code we wrote in Activity 4 was the \texttt{print()} function. This function told \texttt{R} to print into the console whatever we put in the brackets (``Hello World!'').
Same idea with a personalised greeting: if you want to print `Hello Reka', you will need to have ``Hello Reka'' inside the brackets:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{print}\NormalTok{(}\StringTok{"Hello Reka"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "Hello Reka"
\end{verbatim}
There are so many functions in \texttt{R}. We will be learning many of them throughout our class. \texttt{Print} is fun, but most of the time, we will be using functions to help us with our data analysis. For example, getting the minimum, maximum, or mean of a list of numbers. \texttt{R} does this using functions in a very similar way.
For example, if we have a bunch of numbers, we just find the appropriate function to get the summary we want:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{mean}\NormalTok{(}\DecValTok{10}\NormalTok{, }\DecValTok{34}\NormalTok{, }\DecValTok{5}\NormalTok{, }\DecValTok{3}\NormalTok{, }\DecValTok{77}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 10
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{min}\NormalTok{(}\DecValTok{10}\NormalTok{, }\DecValTok{34}\NormalTok{, }\DecValTok{5}\NormalTok{, }\DecValTok{3}\NormalTok{, }\DecValTok{77}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 3
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{max}\NormalTok{(}\DecValTok{10}\NormalTok{, }\DecValTok{34}\NormalTok{, }\DecValTok{5}\NormalTok{, }\DecValTok{3}\NormalTok{, }\DecValTok{77}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 77
\end{verbatim}
How can you find the function you need? Throughout this class, you will learn a list that appears at the top of each lesson. A recommendation is to also create a `function cookbook', where you write down a list of functions, what the functions do, and some examples. Here is an example:
\includegraphics{img/fn_cookbook.png}
You can use google to make your cookbook, and the website \href{https://stackoverflow.com/}{stackoverflow}, in particular, can help you find the function you need. But be wary, especially in the beginning, that you understand what the function does. There can be several different functions for the same action. One good approach is to add a function of interest to your cookbook and ask the teaching team about what it does, and how it might be different to other functions that do the same thing.
\hypertarget{activity-5-play-around-with-functions}{%
\subsubsection{Activity 5: Play around with functions}\label{activity-5-play-around-with-functions}}
Have a guess (or google) about what you think is the function to get the median. Once you have your answer, write it in the shared google docs. Then, use it to get the median of the numbers 10, 34, 5, 3, 77.
Write the answer in your shared google doc (or note it down for yourself if in the quiet room).
The answer is further below, after the note:
\textbf{NOTE:} \texttt{R} is case-sensitive! For example:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Calculating the logarithm }
\FunctionTok{Log}\NormalTok{(}\DecValTok{100}\NormalTok{)}
\CommentTok{\# ERROR!}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Instead, it should be:}
\FunctionTok{log}\NormalTok{(}\DecValTok{100}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 4.60517
\end{verbatim}
Okay, now you know these, the answer to Activity 6 was\ldots{}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{median}\NormalTok{(}\DecValTok{10}\NormalTok{, }\DecValTok{34}\NormalTok{, }\DecValTok{5}\NormalTok{, }\DecValTok{3}\NormalTok{, }\DecValTok{77}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 10
\end{verbatim}
Now let us move on to our second key topic: objects!
\hypertarget{objects}{%
\subsection{Objects}\label{objects}}
Everything that exists in \texttt{R} is an \textbf{object}. Think of objects as boxes where you put things in. Imagine a big, empty cardboard box. We can create this big empty box in R by simply giving it a name. Usually, you want your object/box to have a good descriptive name, which will tell people what is in it. Imagine moving house. If you have a cardboard box full of places, you might want to label it ``plates''. That way, when carrying, you know to be careful, and when unpacking, you know its contents will go in the kitchen. On the other hand, if you named it ``box1'', then this is a lot less helpful when it comes to unpacking.
\hypertarget{activity-6-creating-an-object}{%
\subsubsection{Activity 6: Creating an object}\label{activity-6-creating-an-object}}
Let us create an object called `plates'. To do this, you go to your script, and type `plates'.
\includegraphics{img/plates.png}
But if you run this code, you will get an error. Let's see:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{knitr}\SpecialCharTok{::}\FunctionTok{include\_graphics}\NormalTok{(}\StringTok{\textquotesingle{}img/error\_no\_plates.gif\textquotesingle{}}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\includegraphics[width=400px]{img/error_no_plates}
You see the error `Error! Object plates not found'. This is because you have not yet put anything inside the plates `box'. Remember objects are like boxes,so there must be something inside our object `plates'. In order for this object to exist, you have to put something inside it, or in \texttt{R}-speak \emph{assign it some value}.
Therefore, we make an object by using an \emph{assignment operator} ( \texttt{\textless{}-} ). In other words, we assign something to an object (i.e., put something in the box). For example:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{plates }\OtherTok{\textless{}{-}} \StringTok{"yellow plate"}
\end{Highlighting}
\end{Shaded}
Now if we run this, we will see no error message, but instead, we will see the \texttt{plates} object appear in our \emph{environment pane}:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{knitr}\SpecialCharTok{::}\FunctionTok{include\_graphics}\NormalTok{(}\StringTok{\textquotesingle{}img/assign\_plates.gif\textquotesingle{}}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\includegraphics[width=400px]{img/assign_plates}
Here are some more examples to illustrate:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Putting \textquotesingle{}10\textquotesingle{} in the \textquotesingle{}a\textquotesingle{} box}
\NormalTok{a }\OtherTok{\textless{}{-}} \DecValTok{10}
\CommentTok{\# Putting \textquotesingle{}Hello!\textquotesingle{} in the \textquotesingle{}abc123\textquotesingle{} box}
\NormalTok{abc123 }\OtherTok{\textless{}{-}} \StringTok{"Hello!"}
\end{Highlighting}
\end{Shaded}
In these examples, we are putting the value of \texttt{10} into the object \texttt{a}, and the value of `Hello!' into the object \texttt{abc123}.
Earlier, we introduced you to the Environment and History pane. We mentioned that it lists objects you defined. After making the `a' and `abc123' objects, they should appear in that very pane under the \texttt{Environment} tab.
\hypertarget{types-of-objects}{%
\subsubsection{Types of objects}\label{types-of-objects}}
Why are objects important? We will be storing everything in our data analysis process in these objects. Depending on what is inside them, they can become a different type of object. Here are some examples:
\textbf{Data structures} are important objects that store your data, and there are five main types but we focus on three for this course:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
\emph{(atomic) vector}: an ordered set of elements that are of the same \emph{class}. Vectors are a basic data structure in \texttt{R}. Below are five different classes of vectors:
\end{enumerate}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# 1. numeric vector with three elements}
\NormalTok{my\_1st\_vector }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\FloatTok{0.5}\NormalTok{, }\FloatTok{8.9}\NormalTok{, }\FloatTok{0.6}\NormalTok{) }
\CommentTok{\# 2. integer vector with addition of L at the end of the value}
\NormalTok{my\_2nd\_vector }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(1L, 2L, 3L) }
\CommentTok{\# 3. logical vector}
\NormalTok{my\_3rd\_vector }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\ConstantTok{TRUE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{, }\ConstantTok{FALSE}\NormalTok{) }
\CommentTok{\# \textquotesingle{}my\_4th\_vector\textquotesingle{} creates a logical vector using abbreviations of True and False, but you should use the full words instead}
\NormalTok{my\_4th\_vector }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(T, F) }
\CommentTok{\# 4. character vector}
\NormalTok{my\_5th\_vector }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"a"}\NormalTok{, }\StringTok{"b"}\NormalTok{, }\StringTok{"c"}\NormalTok{) }
\CommentTok{\# 5. complex vector (we will not use this for our class)}
\NormalTok{my\_6th\_vector }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\DecValTok{1}\SpecialCharTok{+}\NormalTok{0i, }\DecValTok{2}\SpecialCharTok{+}\NormalTok{4i) }
\end{Highlighting}
\end{Shaded}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{1}
\tightlist
\item
\emph{lists}: technically they, too, are vectors but they are more complex because they are not restricted on the length, structure, or class of the included elements. For example, to create a list containing strings, numbers, vectors and a logical, use the \texttt{list()} function, and inside the brackets, put everything tat you want to combine into a list:
\end{enumerate}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{list\_data }\OtherTok{\textless{}{-}} \FunctionTok{list}\NormalTok{(}\StringTok{"teal"}\NormalTok{, }\StringTok{"sky blue"}\NormalTok{, }\FunctionTok{c}\NormalTok{(}\DecValTok{10}\NormalTok{, }\DecValTok{5}\NormalTok{, }\DecValTok{10}\NormalTok{), }\ConstantTok{TRUE}\NormalTok{, }\FloatTok{68.26}\NormalTok{, }\FloatTok{95.46}\NormalTok{, }\FloatTok{99.7}\NormalTok{) }
\end{Highlighting}
\end{Shaded}
Above, we created \texttt{list\_data}, an object that contains all those things that we put inside the \texttt{list()} function. This function serves to create a list from combining everything that is put inside its brackets.
Use the \texttt{class()} function to confirm that the objects have been defined as a list
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{class}\NormalTok{(list\_data)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "list"
\end{verbatim}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{2}
\tightlist
\item
\emph{data frames}: also stores elements but differ from lists because they are defined by their number of columns and rows; the vectors (columns) must be of the same length. Data frames can contain different classes but each column must be of the same class. For example, if you want to combine some related vectors to make a data frame on violent American cities, use the function \texttt{data.frame()}:
\end{enumerate}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{\# Making some relevant vectors}
\NormalTok{TopVioCities }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"St. Louis"}\NormalTok{, }\StringTok{"Detroit"}\NormalTok{, }\StringTok{"Baltimore"}\NormalTok{) }\CommentTok{\# some violent US cities}
\NormalTok{VioRatePer1k }\OtherTok{=} \FunctionTok{c}\NormalTok{(}\FloatTok{20.8}\NormalTok{, }\FloatTok{20.6}\NormalTok{, }\FloatTok{20.3}\NormalTok{) }\CommentTok{\# their violence rates per 1,000 persons}
\NormalTok{State }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"Missouri"}\NormalTok{, }\StringTok{"Michigan"}\NormalTok{, }\StringTok{"Maryland"}\NormalTok{) }\CommentTok{\# in what states are these cities found}
\CommentTok{\#Join them to make a data frame called \textquotesingle{}df\textquotesingle{}}
\NormalTok{df}\OtherTok{\textless{}{-}}\FunctionTok{data.frame}\NormalTok{(TopVioCities, VioRatePer1k, State)}
\end{Highlighting}
\end{Shaded}
We can then view the data frame, `df', with the \texttt{View()} function:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{View}\NormalTok{(df)}
\end{Highlighting}
\end{Shaded}
\hypertarget{activity-7-doing-things-to-objects}{%
\subsubsection{Activity 7: Doing things to objects}\label{activity-7-doing-things-to-objects}}
We have learned what functions are (i.e., things that do things) and what are objects (i.e., the boxes that hold things). We also saw some functions which helped us create objects. Functions can also do things to objects. For example, we saw the function \texttt{class()} that told us about what kind of object list\_data was, and \texttt{View()} which allowed us to have a look at our dataframe we called \texttt{df}.
Let us look back at our \texttt{plates} object. Remember it was the object that held our kitchen items. We added `yellow plate' to it. Now let us add some more items and let us use the concatenate \texttt{c()} function for this again:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{plates }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\StringTok{"yellow plate"}\NormalTok{, }\StringTok{"purple plate"}\NormalTok{, }\StringTok{"silver plate"}\NormalTok{, }\StringTok{"orange bowl"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Let us say that we suddenly forgot what was in our object called `plates'. Like what we learned earlier, we use the function \texttt{print()} to see what is inside this object:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{print}\NormalTok{(plates)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "yellow plate" "purple plate" "silver plate" "orange bowl"
\end{verbatim}
This can apply to obtaining the mean, the minimum, and maximum. You could assign those statistics to an object this time:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{nums }\OtherTok{\textless{}{-}} \FunctionTok{c}\NormalTok{(}\DecValTok{10}\NormalTok{, }\DecValTok{34}\NormalTok{, }\DecValTok{5}\NormalTok{, }\DecValTok{3}\NormalTok{, }\DecValTok{77}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Now if we want to know the mean, we can take the mean of the object \texttt{nums}, which we just created:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{mean}\NormalTok{(nums)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 25.8
\end{verbatim}
The object we will use most frequently though is data frames. These hold your data in a format whereby each column represents a variable, and each row an observation.
Just earlier, we had created a dataframe called \texttt{df} previously. If you have not yet copied this over into your own \texttt{R\ Studio}, do this now. You should have the object \texttt{df} in your environment. When you run \texttt{View(df)}, you should see this dataset:
\includegraphics{img/df_view.png}
To do something to an entire dataframe, we would use the name of the object (\texttt{df}) to refer to it. In the case of the \texttt{View()} function, we want to see the whole thing, so we will call \texttt{View(df)}. On the other hand, if we want to refer to only one variable in the data, (remember back to term 1 - each varible is held in each column) there is a special notation to do this.
To refer to a variable (column) inside a dataframe, you use:
\(dataframe name + \$ + variable name\)
For example, to refer to the variable \texttt{VioRatePer1k}, we use the notation \texttt{df\$VioRatePer1k}.
And if we wanted to View only that column, we use:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{View}\NormalTok{(df}\SpecialCharTok{$}\NormalTok{VioRatePer1k)}
\end{Highlighting}
\end{Shaded}
You should see:
\includegraphics{img/view_col_only.png}
Say we wanted to know the mean violence rate across our units of analysis, the cities, for example, we would take the numeric column to calculate this:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{mean}\NormalTok{(df}\SpecialCharTok{$}\NormalTok{VioRatePer1k)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 20.56667
\end{verbatim}
\hypertarget{packages}{%
\section{Packages}\label{packages}}
\textbf{Packages} are a very important element of \texttt{R}.
Packages are elements that add the functionality of R. What most packages do is they introduce new functions that allow you to ask R to do new different things. Anybody can write a package, so consequently R packages vary on quality and complexity. You can find packages in different places, as well, from official repositories (which means they have passed a minimum of quality control), something called Git Hub (a webpage where software developers post work in progress), to personal webpages (danger danger!).
Throughout the course, and hopefully afterwards, you will find yourself installing numerous open source software packages that allow \texttt{R} to do new and different things. There are loads of packages out there. In early 2020, there were over 150,000 packages available. Anyone can write one, so you will need to be careful on which ones you use as the quality can vary. Official repositories, like \href{https://cran.r-project.org/}{CRAN}, are your best bet for packages as they will have passed some quality controls.
You can see what packages are available in your local install by looking at the \emph{packages} tab in the \emph{File directory, Plots, Packages} pane.
\includegraphics[width=0.35\textwidth,height=\textheight]{img/packages.png}
A number of the packages we will use belong to a set of packages called \textbf{tidyverse}. These packages help make your data tidy. According to Statistician and Chief Scientist at \texttt{RStudio}, Hadley Wickham, transforming your data into \emph{tidy data} is one of the most important steps of the data analysis process. It will ensure your data are in the format you need to conduct your analyses. We will also be using the simple features package \textbf{sf} and many more associated with spatial data analysis.
Packages can be installed using the \texttt{install.packages()} function. Remember that while you only need to install packages once, they need to be loaded with the \texttt{library()}function each time you open up \texttt{RStudio}. Let us install the package \texttt{dplyr} from \texttt{tidyverse} and load it:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(dplyr)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
##
## Attaching package: 'dplyr'
\end{verbatim}
\begin{verbatim}
## The following objects are masked from 'package:stats':
##
## filter, lag
\end{verbatim}
\begin{verbatim}
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
\end{verbatim}
A lot of code and activity appears in the console. Warnings may manifest. Most of the time, the warnings explain what is being loaded and confirm that the package is successfully loaded. If there is an error, you will have to figure out what the warnings are telling you to successfully load the package. This happens and is normal.
To double check that you have actually installed \texttt{dplyr}, go to that \emph{File Directory, Plots, Packages} pane and click on the \emph{Packages} tab. The list of packages is in alphabetical order and \texttt{dplyr} should be there. If there is a tick in its box, it means that this package is currently loaded and you can use it; if there is no tick, it means that it is inactive, and you will have to bring it up with \texttt{library()}, or just tick its box (Figure 1.6).
\includegraphics[width=0.35\textwidth,height=\textheight]{img/dplyr.png}
On \emph{masking}: sometimes packages introduce functions that have the same name as those that are already loaded into your session. When that happens, the newly loaded ones will override the previous ones. You can still use them but you will have to refer to them explicitly by bringing them up by specifying to which package they belong with \texttt{library()}.
How do you find out what a package does? You look at the relevant documentation. In the Packages window scroll down until you find the new package we installed listed. Here you will see the name of the package (dplyr), a brief description of what the program is about, and the version you have installed (an indication that a package is a good package is that it has gone through several versions, that means that someone is making sure the package gets regular updates and improvements).
Click in the name \emph{dplyr}. You will see that R Studio has now brought you to the Help tab. Here is where you find the help files for this package, including all the available documentation.
Every beginner in R will find these help files a bit confusing. But after a while, their format and structure will begin to make sense to you. Click where it says \emph{User guides, package vignettes, and other documentation}. Documentation in R has become much better since people started to write \textbf{vignettes} for their packages. They are little tutorials that explain with examples what each package does. Click in the \emph{cowsay::cowsay\_tutorial} that you see listed here (the html link). What you will find there is an html file that gives you a detailed tutorial on this package. You don't need to read it now, but remember that this is one way to find help when using R. You will learn to love vignettes.
\hypertarget{exploring-data}{%
\section{Exploring data}\label{exploring-data}}
Now that we know the basic component, let's play around with using R as we will throughout the course, for some data analysis.
We will get some data by installing a package which has data in it as well as functions, and then go on to produce some basic summaries. This should give some practice!
\hypertarget{activity-8-playing-around-with-data}{%
\subsection{Activity 8: Playing around with data}\label{activity-8-playing-around-with-data}}
We are going to look at some data that are part of the \emph{fivethirtyeight} package. This package contains data sets and code behind the stories in \href{http://fivethirtyeight.com/}{this particular online newspaper}. This package is not part of the base installation of R, so you will need to install it first. I won't give you the code for it. See if you can figure it out by looking at previous examples. Discuss and write in the google doc what you think the code will be.
Done? Ok, now we are going to look at the data sets that are included in this package. Remember first we have to load the package if we want to use it:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(}\StringTok{"fivethirtyeight"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Some larger datasets need to be installed separately, like senators and
## house_district_forecast. To install these, we recommend you install the
## fivethirtyeightdata package by running:
## install.packages('fivethirtyeightdata', repos =
## 'https://fivethirtyeightdata.github.io/drat/', type = 'source')
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{data}\NormalTok{(}\AttributeTok{package=}\StringTok{"fivethirtyeight"}\NormalTok{) }\CommentTok{\#This function will return all the data frames that are available in the named package.}
\end{Highlighting}
\end{Shaded}
Notice that this package has some data sets that relate to stories covered in this newspaper that had a criminological angle. Let's look for example at the \texttt{hate\_crimes} data set. How do you that? First we have to load the data frame into our global environment. To do so use the following code:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{data}\NormalTok{(}\StringTok{"hate\_crimes"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
This function will search among all the \emph{loaded} packages and locate the \texttt{hate\_crimes} data set. Notice that it now appears in the global environment, although it also says ``promise'' next to it. To see the data in full you need to do something to it first. So let's do that.
Every object in R can have \textbf{attributes}. These are: names; dimensions (for matrices and arrays: number of rows and columns) and dimensions names; class of object (numeric, character, etc.); length (for a vector this will be the number of elements in the vector); and other user-defined. You can access the attributes of an object using the \texttt{attributes()} function. Let's query R for the attributes of this data frame.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{attributes}\NormalTok{(hate\_crimes)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## $row.names
## [1] 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] 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] 51
##
## $class
## [1] "tbl_df" "tbl" "data.frame"
##
## $names
## [1] "state" "state_abbrev"
## [3] "median_house_inc" "share_unemp_seas"
## [5] "share_pop_metro" "share_pop_hs"
## [7] "share_non_citizen" "share_white_poverty"
## [9] "gini_index" "share_non_white"
## [11] "share_vote_trump" "hate_crimes_per_100k_splc"
## [13] "avg_hatecrimes_per_100k_fbi"
\end{verbatim}
This prints out the row names (not very exciting here..) the class (see above when we used \texttt{class()} function) and the names, which are the column headers - or the \emph{names of the variables within this data set}. You can see there are things like state, and share who voted trump (in the 2016 election, not most recent!).
Now use the \texttt{View()} function to glance at your data frame. What you get there is a spreadsheet with 12 variables and 51 observations. Each variable in this case is providing you with information (demographics, voting patterns, and hate crime) about each of the US states.
Ok, let's now have a quick look at the data. There are so many different ways of producing summary stats for data stored in R that is impossible to cover them all! We will just introduce a few functions that you may find useful for summarising data. Before we do any of that it is important you get a sense for what is available in this data set. Go to the help tab and in the search box input the name of the data frame, this will take you to the documentation for this data frame. Here you can see a list of the available variables.
\includegraphics{img/codebook.png}
Let's start with the \emph{mean}. This function takes as an argument the numeric variable for which you want to obtain the mean. You have done this above, so it should be familiar now! If you want to obtain the mean of the variable that gives us the proportion of people that voted for Donald Trump you can use the following expression:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{mean}\NormalTok{(hate\_crimes}\SpecialCharTok{$}\NormalTok{share\_vote\_trump)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] 0.49
\end{verbatim}
Another function you may want to use with numeric variables is \texttt{summary()}:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{summary}\NormalTok{(hate\_crimes}\SpecialCharTok{$}\NormalTok{share\_vote\_trump)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.040 0.415 0.490 0.490 0.575 0.700
\end{verbatim}
This gives you the five number summary (minimum, first quartile, median, third quartile, and maximum, plus the mean and the count of missing values if there are any).
You don't have to specify a variable you can ask for these summaries from the whole data frame:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{summary}\NormalTok{(hate\_crimes)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## state state_abbrev median_house_inc share_unemp_seas
## Length:51 Length:51 Min. :35521 Min. :0.02800
## Class :character Class :character 1st Qu.:48657 1st Qu.:0.04200
## Mode :character Mode :character Median :54916 Median :0.05100
## Mean :55224 Mean :0.04957
## 3rd Qu.:60719 3rd Qu.:0.05750
## Max. :76165 Max. :0.07300
##
## share_pop_metro share_pop_hs share_non_citizen share_white_poverty
## Min. :0.3100 Min. :0.7990 Min. :0.01000 Min. :0.04000
## 1st Qu.:0.6300 1st Qu.:0.8405 1st Qu.:0.03000 1st Qu.:0.07500
## Median :0.7900 Median :0.8740 Median :0.04500 Median :0.09000
## Mean :0.7502 Mean :0.8691 Mean :0.05458 Mean :0.09176
## 3rd Qu.:0.8950 3rd Qu.:0.8980 3rd Qu.:0.08000 3rd Qu.:0.10000
## Max. :1.0000 Max. :0.9180 Max. :0.13000 Max. :0.17000
## NA's :3
## gini_index share_non_white share_vote_trump hate_crimes_per_100k_splc
## Min. :0.4190 Min. :0.0600 Min. :0.040 Min. :0.06745
## 1st Qu.:0.4400 1st Qu.:0.1950 1st Qu.:0.415 1st Qu.:0.14271
## Median :0.4540 Median :0.2800 Median :0.490 Median :0.22620
## Mean :0.4538 Mean :0.3157 Mean :0.490 Mean :0.30409
## 3rd Qu.:0.4665 3rd Qu.:0.4200 3rd Qu.:0.575 3rd Qu.:0.35694
## Max. :0.5320 Max. :0.8100 Max. :0.700 Max. :1.52230
## NA's :4
## avg_hatecrimes_per_100k_fbi
## Min. : 0.2669
## 1st Qu.: 1.2931
## Median : 1.9871
## Mean : 2.3676
## 3rd Qu.: 3.1843
## Max. :10.9535
## NA's :1
\end{verbatim}
There are multiple ways of getting results in R. Particularly for basic and intermediate-level statistical analysis many core functions and packages can give you the answer that you are looking for. For example, there are a variety of packages that allow you to look at summary statistics using functions defined within those packages. You will need to install these packages before you can use them.
I am only going to introduce one of them here \texttt{skimr}. You will need to install it before anything else.
Once you have loaded the \emph{skimr} package you can use it. Its main function is \emph{skim}. Like \emph{summary} for data frames, skim presents results for all the columns and the statistics will depend on the class of the variable.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{skim}\NormalTok{(hate\_crimes)}
\end{Highlighting}
\end{Shaded}
Hopefully in your statistical modules you had taken previously, you have learned some things about how to graphically display variables. So you may have some memory about the amount of work involved with this. Hopefully R will offer some respite. Of course, there are many different ways of producing graphics in R. In this course we rely on a package called \emph{ggplot2}, which is part of the tidyverse set of packages mentioned earlier.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{library}\NormalTok{(ggplot2)}
\end{Highlighting}
\end{Shaded}
Then we will use one of its functions to create a scatterplot.
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{ggplot}\NormalTok{(hate\_crimes, }\FunctionTok{aes}\NormalTok{(}\AttributeTok{x=}\NormalTok{share\_vote\_trump, }\AttributeTok{y=}\NormalTok{avg\_hatecrimes\_per\_100k\_fbi)) }\SpecialCharTok{+}
\FunctionTok{geom\_point}\NormalTok{(}\AttributeTok{shape=}\DecValTok{1}\NormalTok{) }\SpecialCharTok{+}
\FunctionTok{geom\_smooth}\NormalTok{(}\AttributeTok{method=}\NormalTok{lm)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## `geom_smooth()` using formula 'y ~ x'
\end{verbatim}
\begin{verbatim}
## Warning: Removed 1 rows containing non-finite values (stat_smooth).
\end{verbatim}
\begin{verbatim}
## Warning: Removed 1 rows containing missing values (geom_point).
\end{verbatim}
\includegraphics{crime_mapping_textbook_files/figure-latex/unnamed-chunk-23-1.pdf}
What do you think this graphic is telling you? Discuss and write in your shared google docs.
Graphing is very powerful in R, and much of the spatial visualisation we will produce throughout the module will build on this. If you are not already familiar with this, I recommend a read of the data visualisation chapter of R for Data Science \url{https://r4ds.had.co.nz/data-visualisation.html}
\hypertarget{getting-organised-r-projects}{%
\section{Getting organised: R Projects}\label{getting-organised-r-projects}}
One thing that can help you tremendously throughout this module is keeping your code organised.R Studio helps with this by virtue of something called \textbf{R Projects}.
Technically, a R Studio project is just a directory with the name of the project, and a few files and folders created by R Studio for internal purposes. This is where you should hold your scripts, your data, and reports. You can manage this folder with your own operating system manager (discussed earlier, e.g., Windows) or through the R Studio file manager (that you access in the bottom right corner set of windows in R Studio).
When a project is reopened, R Studio opens every file and data view that was open when the project was closed last time around. Trust me, this is a really helpful thing! If you create a project for this module, you can keep everything in once place, and refer back to your old code and your learnings throughout the module.
\hypertarget{activity-9-saving-your-work-and-projects}{%
\subsubsection{Activity 9: Saving your work and projects}\label{activity-9-saving-your-work-and-projects}}
First things first, hopefully you have already created a separate folder on your desktop, or dropbox, or something like this. Now save the script you've been working on into this folder. By clicking on ``File'' and ``Save as\ldots{}''.
\includegraphics{img/save_script_as.png}
Then navigate to your folder for this module, and for your script make sure to give it some meaningful name like week1lab.R or something like this. Then click `save'.
\includegraphics{img/rename_and_save.png}
Now, go back to ``File'' and select ``New project\ldots{}''
\includegraphics{img/file_newproj.png}
Then in the options that appear choose ``Existing Directory''. This is because you already have a folder for this work, this is where you saved your script just before. For me this was my folder called `crime\_mapping' you saw above.
\includegraphics{img/existing_dir.png}
So select `Existing Directory', and on the next page use the ``Browse'' button to select this folder (the directory) where you saved the script earlier. Once you have done this, click on `Create Project' on the bottom.