-
Notifications
You must be signed in to change notification settings - Fork 2
/
mapsR.tex
2144 lines (1811 loc) · 85.1 KB
/
mapsR.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[]{report}
\usepackage{lmodern}
\usepackage{setspace}
\setstretch{1}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\else % if luatex or xelatex
\ifxetex
\usepackage{mathspec}
\else
\usepackage{fontspec}
\fi
\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\usepackage[margin=1in]{geometry}
\usepackage{hyperref}
\hypersetup{unicode=true,
pdftitle={How to create and edit maps with R},
pdfauthor={Kévin Cazelles},
pdfborder={0 0 0},
breaklinks=true}
\urlstyle{same} % don't use monospace 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{graphicx,grffile}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{5}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
%%% Use protect on footnotes to avoid problems with footnotes in titles
\let\rmarkdownfootnote\footnote%
\def\footnote{\protect\rmarkdownfootnote}
%%% Change title format to be more compact
\usepackage{titling}
% Create subtitle command for use in maketitle
\newcommand{\subtitle}[1]{
\posttitle{
\begin{center}\large#1\end{center}
}
}
\setlength{\droptitle}{-2em}
\title{How to create and edit maps with R}
\pretitle{\vspace{\droptitle}\centering\huge}
\posttitle{\par}
\author{Kévin Cazelles}
\preauthor{\centering\large\emph}
\postauthor{\par}
\predate{\centering\large\emph}
\postdate{\par}
\date{March 31, 2015}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[CO,CE]{}
\fancyfoot[CO,CE]{Making maps with R}
\fancyfoot[LE,RO]{\thepage}
\begin{document}
\maketitle
\begin{abstract}
This manuals is dedicated to readers who wants to get started with map
creation and edition in R. It provides a basic understanding of the
fundamental packages and functions required to turn R into an efficient
Geographic Information System (GIS). It also shows how to manipulated
the spatial objects defined. It is however beyond the range of this
document to present exhaustively the potentialities R offers in term of
spatial manipulations and analyses. Rather, it focuses on explaining
what are the essential classes of spatial objects and the methods that
can be applied and pinpoints valuable resources for readers who want to
go further.
\end{abstract}
Ce document est distribu\'{e} sous les termes de la licence CC-BY-NC-SA 4.0, licence de libre diffusion soumise à certaines conditions. En accord avec cette licence, vous pouvez librement utiliser, adapter, modifier et redistribuer le contenu de ce document dans n'importe quelle circonstance, sauf à des fins commerciales (NC), et à la condition non-n\'{e}gociable qu’un cr\'{e}dit suffisant soit attribu\'{e} à l'auteur de ce pr\'{e}sent document en citant leurs noms (BY). Toute version modifi\'{e}e et redistribu\'{e}e sera r\'{e}gie par les m\^{e}mes termes (SA). Ces droits et conditions seront valides tant que le pr\'{e}sent travail sera plac\'{e} sous les termes de cette licence.
\begin{center}
\includegraphics[width=.28\textwidth]{aux/ccbyncsa.png}
\end{center}
\newpage
{
\setcounter{tocdepth}{2}
\tableofcontents
}
\listoffigures
\hypertarget{introduction}{%
\chapter{Introduction}\label{introduction}}
Since the last decade, new softwares have emerged making the creation
and edition of maps accessible to all. Scientists can now readily draw
valuable spatial representations of their work without deep knowledge in
mapping\footnote{I recommend the reading of the article:
\href{http://www.nature.com/news/data-visualization-science-on-the-map-1.17024}{Zastrow,
Mark. 2015. ``Science on the Map.'' Nature 519: 119--120.}}. Basic
mapping skills should be a part of educational background of most of
scientists as maps are often a proper way to expose facts and thereby
relevant representations that may ease the scientific debate. Among the
tools available (see below) some Geographic Information System (GIS) are
free, open-source such as \href{http://qgis.org/en/site/}{Quantum GIS}
and \href{http://grass.osgeo.org}{GRASS GIS}. Also, some high-level
programming languages such as JavaScript, Python, or R offer dedicated
packages. Few software are listed a couple of softwares:
\begin{itemize}
\tightlist
\item
\href{http://www.arcgis.com/features/}{ArcGIS}
\item
\href{http://cartodb.com}{CartoDB}
\item
\href{http://www.diva-gis.org}{DIVA-GIS}
\item
\href{http://geojson.io/\#map=2/20.0/0.0}{GeoJson}
\item
\href{https://www.google.fr/maps}{Google Map}
\item
\href{http://www.google.fr/intl/eng/earth/index.html}{Goole Earth}
\item
\href{http://grass.osgeo.org}{GRASS}
\item
\href{http://leafletjs.com}{Leaflet}
\item
\href{http://www.mapinfo.com}{Mapinfo}
\item
\href{http://mapnik.org}{Mapnik}
\item
\href{http://www.postgis.org}{PostGIS}
\item
\href{http://qgis.org/en/site/}{Quantum GIS}
\item
\href{http://www.saga-gis.org/en/index.html}{SAGA GIS}
\item
\href{https://www.mapbox.com/tilemill/}{TileMill}
\end{itemize}
\hypertarget{why-use-r-for-mapping}{%
\section{Why use R for mapping?}\label{why-use-r-for-mapping}}
Given the number of tools dedicated to visualization and analyses of
spatial data, it is important that users ask this question and take some
time and balance pros ans cons. According to me, the choice strongly
relies upon (i) your ambition in term of mapping and (ii) your R skills.
If you aim at creating a good-looking map without analysis and you are
not familiar with R, I would discourage you to use R. But if you are
familiar with R, you can quickly get a map as a R plot and so benefit
from the plot system you already know. Also, when you need tricky
spatial analysis (\emph{e.g} krigging), even if you are not familiar
with R, you may benefit from this language and you may not encounter any
difficulties to realize any kind of analysis and gather the plot.
Ultimately yo will analysis and create your plot with R only.
\hypertarget{what-can-be-found-in-this-document}{%
\section{What can be found in this
document?}\label{what-can-be-found-in-this-document}}
This short document provides some basics to create and edit maps using
\href{https://cran.r-project.org}{R}. One of the strongest advantage of
using R as a Geographic Information System (GIS) is to use its
facilities to manipulate efficiently spatial object and to undertake
various spatial analysis. The spatial analysis are beyond the scope of
this document. I will deal with the manipulation of spatial objects: I
start by explaining how spatial classes work in R, then I show you how R
can import and export spatial objects. The latter makes R a useful tool
to create, manipulate and convert files that contain spatial data.
Throughout the document I strive to provide advices (as good as
possible) to edit simple but elegant maps.
To be able to use all the code below, four packages must be installed:
``sp'', ``raster'', ``rgdal'', ``rgeos''. Their installation will be
explained along the document. To take maximum benefits from the present
document you must be working on line. As the reader of this document,
you must have basic R skills, meaning the user knows how to use object,
how to code basic functions and how to edit plots. If it not the case,
you may benefit from a clear introduction to R such as the one available
on the
\href{http://cran.r-project.org/doc/manuals/r-release/R-intro.html}{CRAN
website}.
If the reader of the present document is eager to learn more about the
potentialities R offers, a good starting point is to read the valuable
\href{http://cran.r-project.org/web/views/Spatial.html}{package guide}
Roger Bivand - one of the most important contributor to spatial analysis
in R - wrote. You can also pursue your learning by having a look of the
\href{http://link.springer.com/book/10.1007/978-1-4614-7618-4}{book} the
same author wrote with two colleagues.
\hypertarget{colophon}{%
\section{Colophon}\label{colophon}}
The present document has been written using
\href{http://rmarkdown.rstudio.com/authoring_rcodechunks.html}{R
Markdown} on MacOSX 10.10.4. I conceived the code to make it working
standalone: additional material is downloaded from R commands. Also,
instead of a reference list, I provide hyper-links to better explain
what we do when we use spatial object in R. The version of R that
creates the document is:
As a convention, I use bold fonts for R objects and I add parentheses
for objects that are functions (\emph{e.g.}, object \textbf{obj} and
function \textbf{foo()}). I use italics for class and function arguments
(for instance, argument \emph{arg}) and I employ quotemarks for package
names (\emph{e.g}, package ``sp''). Also, \emph{path} denotes the
character string that contains the path of the ``.Rmd'' file that
generates this document. If you find some error or have any comments
about this document and/or the script, please feel free to send me an
email (kevin(dot)cazelles(at)gmail(dot)com).
Many functions are used throughout this document and some are not
detailed. Whenever you want to get more details, I recommend you to read
the documentation associated. To get access to this documentation, you
need to type ``?'' before the name of the function then press Enter in
the R console. The example below shows two commands to access the help
associated to the \textbf{getwd()} function.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{?getwd}
\KeywordTok{help}\NormalTok{(}\StringTok{"getwd"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\hypertarget{points-lines-polygons-and-grids}{%
\chapter{Points, Lines, Polygons and
Grids}\label{points-lines-polygons-and-grids}}
Basically, spatial objects are split into two categories: vectors and
rasters. Roughly speaking, vectors are a set of coordinates, whereas
rasters are regular grids. The first step to create a map is to
manipulate points, lines and grids (polygons can be considered as a sets
of closed lines). This is what I present in this section. At first
glance, one can describe our planet as a sphere and locate any point on
Earth by two values: the longitude (values taken in {[}-180,180{]}) and
the latitude (values taken in {[}-90,90{]})\footnote{Obviously, there
are many ways to locate points on Earth.}. For the sake of
illustration, I define a object \textbf{vec} that contains the
coordinates of 10 points randomly distributed on Earth .
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{nbp <-}\StringTok{ }\DecValTok{10}
\NormalTok{vec <-}\StringTok{ }\KeywordTok{list}\NormalTok{(}\DataTypeTok{x=}\KeywordTok{runif}\NormalTok{(nbp,}\OperatorTok{-}\DecValTok{160}\NormalTok{,}\DecValTok{160}\NormalTok{), }\DataTypeTok{y=}\KeywordTok{runif}\NormalTok{(nbp,}\OperatorTok{-}\DecValTok{80}\NormalTok{,}\DecValTok{80}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ras <-}\StringTok{ }\KeywordTok{matrix}\NormalTok{(}\KeywordTok{runif}\NormalTok{(nbp}\OperatorTok{*}\NormalTok{nbp),nbp)}
\end{Highlighting}
\end{Shaded}
To keep things as simple as possible, that is all that should be
defined! Drawing very basic maps is no more that plotting these objects:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Split the plot region into four subregions, the box is of "L" form.}
\KeywordTok{par}\NormalTok{(}\DataTypeTok{mfrow=}\KeywordTok{c}\NormalTok{(}\DecValTok{2}\NormalTok{,}\DecValTok{2}\NormalTok{), }\DataTypeTok{bty=}\StringTok{"l"}\NormalTok{)}
\NormalTok{## ----}
\KeywordTok{plot}\NormalTok{(}\KeywordTok{c}\NormalTok{(}\OperatorTok{-}\DecValTok{180}\NormalTok{,}\OperatorTok{+}\DecValTok{180}\NormalTok{),}\KeywordTok{c}\NormalTok{(}\OperatorTok{-}\DecValTok{90}\NormalTok{,}\DecValTok{90}\NormalTok{), }\DataTypeTok{col=}\DecValTok{0}\NormalTok{, }\DataTypeTok{main=}\StringTok{"Points"}\NormalTok{, }\DataTypeTok{xlab=}\StringTok{""}\NormalTok{, }\DataTypeTok{ylab=}\StringTok{"Latitude (°)"}\NormalTok{)}
\KeywordTok{points}\NormalTok{(vec, }\DataTypeTok{pch=}\DecValTok{19}\NormalTok{, }\DataTypeTok{col=}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\StringTok{"grey45"}\NormalTok{))}
\KeywordTok{text}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x, vec}\OperatorTok{$}\NormalTok{y, }\DecValTok{1}\OperatorTok{:}\DecValTok{10}\NormalTok{, }\DataTypeTok{pos=}\DecValTok{3}\NormalTok{, }\DataTypeTok{col=}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\StringTok{"grey45"}\NormalTok{))}
\NormalTok{## ----}
\KeywordTok{plot}\NormalTok{(}\KeywordTok{c}\NormalTok{(}\OperatorTok{-}\DecValTok{180}\NormalTok{,}\OperatorTok{+}\DecValTok{180}\NormalTok{),}\KeywordTok{c}\NormalTok{(}\OperatorTok{-}\DecValTok{90}\NormalTok{,}\DecValTok{90}\NormalTok{), }\DataTypeTok{col=}\DecValTok{0}\NormalTok{, }\DataTypeTok{main=}\StringTok{"Lines"}\NormalTok{, }\DataTypeTok{xlab=}\StringTok{""}\NormalTok{, }\DataTypeTok{ylab=}\StringTok{""}\NormalTok{)}
\KeywordTok{lines}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{1}\OperatorTok{:}\DecValTok{4}\NormalTok{], vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{1}\OperatorTok{:}\DecValTok{4}\NormalTok{])}
\KeywordTok{lines}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{5}\OperatorTok{:}\DecValTok{6}\NormalTok{], vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{5}\OperatorTok{:}\DecValTok{6}\NormalTok{], }\DataTypeTok{col=}\DecValTok{2}\NormalTok{)}
\KeywordTok{lines}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{7}\OperatorTok{:}\DecValTok{10}\NormalTok{], vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{7}\OperatorTok{:}\DecValTok{10}\NormalTok{], }\DataTypeTok{col=}\DecValTok{3}\NormalTok{)}
\NormalTok{## ----}
\KeywordTok{plot}\NormalTok{(}\KeywordTok{c}\NormalTok{(}\OperatorTok{-}\DecValTok{180}\NormalTok{,}\OperatorTok{+}\DecValTok{180}\NormalTok{),}\KeywordTok{c}\NormalTok{(}\OperatorTok{-}\DecValTok{90}\NormalTok{,}\DecValTok{90}\NormalTok{), }\DataTypeTok{col=}\DecValTok{0}\NormalTok{, }\DataTypeTok{main=}\StringTok{"Polygon"}\NormalTok{, }\DataTypeTok{xlab=}\StringTok{"Longitude (°)"}\NormalTok{,}
\DataTypeTok{ylab=}\StringTok{"Latitude (°)"}\NormalTok{)}
\KeywordTok{polygon}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{1}\OperatorTok{:}\DecValTok{6}\NormalTok{], vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{1}\OperatorTok{:}\DecValTok{6}\NormalTok{], }\DataTypeTok{col=}\DecValTok{2}\NormalTok{, }\DataTypeTok{lwd=}\DecValTok{4}\NormalTok{, }\DataTypeTok{border=}\DecValTok{4}\NormalTok{)}
\NormalTok{## ----}
\KeywordTok{image}\NormalTok{(}\KeywordTok{seq}\NormalTok{(}\OperatorTok{-}\DecValTok{120}\NormalTok{,}\DecValTok{120}\NormalTok{,}\DataTypeTok{length.out=}\DecValTok{11}\NormalTok{), }\KeywordTok{seq}\NormalTok{(}\OperatorTok{-}\DecValTok{60}\NormalTok{,}\DecValTok{60}\NormalTok{,}\DataTypeTok{length.out=}\DecValTok{11}\NormalTok{), ras, }\DataTypeTok{main=}\StringTok{"Grid"}\NormalTok{,}
\DataTypeTok{xlab=}\StringTok{"Longitude (°)"}\NormalTok{, }\DataTypeTok{ylab=}\StringTok{""}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{figure}
\centering
\includegraphics{mapsR_files/figure-latex/unnamed-chunk-6-1.pdf}
\caption{\label{fig1}Points, lines, polygons and grids. These are the
basic object manipulated when drawing maps.}
\end{figure}
\hypertarget{classes-for-spatial-objects-in-r}{%
\chapter{Classes for spatial objects in
R}\label{classes-for-spatial-objects-in-r}}
\hypertarget{the-sp-package}{%
\section{The ``sp'' package}\label{the-sp-package}}
Manipulating efficiently spatial data requires more than graphical
skills. Indeed, spatial operations often involve to associate spatial
objects with datasets or with a Coordinate Reference System (CRS). To
provide a consistent framework to work with spatial objects in R, the
``sp'' package defines adequate classes and methods. These classes of
spatial objects are used by other packages (such as ``rgdal'', ``rgeos''
and ``raster'' that are used below) which makes R a powerful GIS:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{install.packages}\NormalTok{(}\StringTok{"sp"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
The documentation of this package and any package found on the
\href{http://cran.r-project.org/doc/manuals/r-release/R-intro.html}{CRAN
website} is available as a pdf file. For the ``sp'' package, you can
either look at the
\href{http://cran.r-project.org/web/packages/sp/index.html}{reference
manual} on line or you can enter the following command line in your R
console:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(}\DataTypeTok{help=}\StringTok{"sp"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Then I load the package\footnote{Loading a package prevents you from
using the name space of the package, ``sp::'' for ``sp'' package,
before each function.}:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(}\StringTok{"sp"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
The ``sp'' package is the core package to turn R into a powerful
GIS\footnote{Contributed packages extent a lot R functionalities. The
number of \href{https://cran.r-project.org/web/packages/}{contributed
package} increases exponentially since its first release (June 2000);
on the August 12, 2015, 7002 contributed packages were available.} and
the other packages that will be used depend on it. The table below
present the spatial classes that are used in this document. To create an
object of any of those classes, the function to be called is named after
the class of object it returns.
\begin{longtable}[]{@{}ll@{}}
\caption{Summary of the spatial classes defined by the ``sp'' package
that will be detail in this document.}\tabularnewline
\toprule
Classes / Functions & Contents\tabularnewline
\midrule
\endfirsthead
\toprule
Classes / Functions & Contents\tabularnewline
\midrule
\endhead
Points & list of points (set of coordinates)\tabularnewline
SpatialPoints & list of points + CRS\tabularnewline
SpatialPointsDataPoints & list of points + CRS + attribute
table\tabularnewline
Line & a line (set of coordinates)\tabularnewline
Lines & list of lines\tabularnewline
SpatialLines & list of lines + CRS\tabularnewline
SpatialLinesDataFrame & list of lines + CRS + attribute
table\tabularnewline
Polygon & a polygon (set of coordinates)\tabularnewline
Polygons & list of polygons\tabularnewline
SpatialPolygons & list of polygons + CRS\tabularnewline
SpatialPolygonsDataFrame & list of polygons + CRS + attribute
table\tabularnewline
GridTopology & Grid (smallest coordinates + cell size and
number)\tabularnewline
SpatialGrids & Grid + CRS\tabularnewline
SpatialGridsDataFrame & Grid + CRS + attribute table\tabularnewline
\bottomrule
\end{longtable}
\hypertarget{spatial-points}{%
\section{Spatial points}\label{spatial-points}}
\hypertarget{class-spatialpoints}{%
\subsection{\texorpdfstring{Class
\emph{SpatialPoints}}{Class SpatialPoints}}\label{class-spatialpoints}}
Now, I re-use the coordinates that \textbf{vec} countains and I call the
\textbf{SpatialPoints()} function to get an object of class
\emph{SpatialPoints}.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ptsp <-}\StringTok{ }\KeywordTok{SpatialPoints}\NormalTok{(vec)}
\KeywordTok{print}\NormalTok{(ptsp)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## class : SpatialPoints
## features : 10
## extent : -154.7469, 151.8235, -72.64904, 69.68905 (xmin, xmax, ymin, ymax)
## coord. ref. : NA
\end{verbatim}
Hence, an object of class \emph{SpatialPoints} is created. You may have
noticed that no CRS is defined. At this stage, it is optional. It can be
defined with the \emph{proj4string} that is encountered each time a CRS
can be associate a CRS to your object. Note that the way it actually
works is detailed in section {[}The ``rgdal'' package{]}{[}{]}. Below, I
specify that longitude and latitude will be used together with the
\href{http://en.wikipedia.org/wiki/Geodetic_datum}{geodetic datum} WGS84
(the most common).
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ptsp <-}\StringTok{ }\KeywordTok{SpatialPoints}\NormalTok{(vec, }\DataTypeTok{proj4string=}\KeywordTok{CRS}\NormalTok{(}\StringTok{"+proj=longlat +datum=WGS84 +ellps=WGS84"}\NormalTok{))}
\KeywordTok{print}\NormalTok{(ptsp)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## class : SpatialPoints
## features : 10
## extent : -154.7469, 151.8235, -72.64904, 69.68905 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{plot}\NormalTok{(ptsp)}
\end{Highlighting}
\end{Shaded}
\begin{figure}
\centering
\includegraphics{mapsR_files/figure-latex/unnamed-chunk-11-1.pdf}
\caption{Spatial points and the default plot associated.}
\end{figure}
This plot differs from the one drawn in the previous section! This is
because there is a specific \textbf{plot()} method for spatial
object\footnote{To list all the different \textbf{plot()} methods, you
can enter ``methods(plot)'' in the R console.}. This method is very
helpful, especially the \emph{add} argument that allows us to add
spatial objects on a base map. Now, I get a closer look at the
newly-defined spatial object.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{isS4}\NormalTok{(ptsp)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] TRUE
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{structure}\NormalTok{(ptsp)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## class : SpatialPoints
## features : 10
## extent : -154.7469, 151.8235, -72.64904, 69.68905 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
\end{verbatim}
It is a S4 object\footnote{Roughly speaking, objects in R are of two
different kinds: S3 and S4. The first one is somehow more flexible
while the latter is more formal. For more details, I recommend you to
read \href{http://adv-r.had.co.nz/OO-essentials.html}{what Hadley
Wickham wrote about it}.}, let's look at its attributes:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{attributes}\NormalTok{(ptsp)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## $bbox
## min max
## x -154.74686 151.82353
## y -72.64904 69.68905
##
## $proj4string
## CRS arguments:
## +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
##
## $coords
## x y
## [1,] -126.951509 -72.64904
## [2,] -18.450404 -47.97414
## [3,] -2.931689 -58.84770
## [4,] 9.235156 69.68905
## [5,] 82.904335 49.69026
## [6,] 33.599190 -37.76025
## [7,] -154.746863 33.46986
## [8,] -112.062220 -52.75116
## [9,] 151.823532 -46.35134
## [10,] 135.825774 -67.28474
##
## $class
## [1] "SpatialPoints"
## attr(,"package")
## [1] "sp"
\end{verbatim}
One way to access to these attributes is given below:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Let's call ptsp's extent}
\KeywordTok{attributes}\NormalTok{(ptsp)}\OperatorTok{$}\NormalTok{bbox}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## min max
## x -154.74686 151.82353
## y -72.64904 69.68905
\end{verbatim}
Some attributes are slots that can be called using ``@'':
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{slotNames}\NormalTok{(ptsp)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "coords" "bbox" "proj4string"
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Let's call ptsp's proj4string}
\NormalTok{ptsp}\OperatorTok{@}\NormalTok{proj4string}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## CRS arguments:
## +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
\end{verbatim}
This is a powerful way to access any piece of information that spatial
objects contain.
\hypertarget{class-spatialpointsdataframe}{%
\subsection{\texorpdfstring{Class
\emph{SpatialPointsDataFrame}}{Class SpatialPointsDataFrame}}\label{class-spatialpointsdataframe}}
In spatial analysis, data may be associated with coordinates. For
vectors, data are stored in an attribute table. For instance, consider
you have geographic coordinates for different points corresponding to
different soil sample. To store the soil organic matter and/or the
percentage of clay associated to each sample, an attribute table must be
created. In R, creating a data is very straightforward thanks to the
\textbf{data.frame()} that creates \emph{data.frame} object:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Brackets are used to print the table.}
\NormalTok{(datapt <-}\StringTok{ }\KeywordTok{data.frame}\NormalTok{(}\KeywordTok{cbind}\NormalTok{(}\DataTypeTok{Var1=}\KeywordTok{rnorm}\NormalTok{(nbp), }\DataTypeTok{Var2=}\DecValTok{1}\OperatorTok{+}\KeywordTok{runif}\NormalTok{(nbp,}\DecValTok{0}\NormalTok{,}\DecValTok{10}\NormalTok{))))}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Var1 Var2
## 1 0.4423867 6.998069
## 2 0.6989734 9.859475
## 3 0.1653101 6.369589
## 4 0.4880717 9.215309
## 5 0.2906447 1.299671
## 6 0.6872198 8.584681
## 7 -1.3119996 6.364737
## 8 -0.4560925 5.838437
## 9 1.3140913 5.232988
## 10 -0.4708950 2.251813
\end{verbatim}
Given one \emph{SpatialPoints} object together with one
\emph{data.frame}, I create a \emph{SpatialPointsDataframe} object. It
contains all attributes you can find in a
\href{https://en.wikipedia.org/wiki/Shapefile}{Shapefile} of points.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ptspd <-}\StringTok{ }\KeywordTok{SpatialPointsDataFrame}\NormalTok{(ptsp, }\DataTypeTok{data=}\NormalTok{datapt)}
\KeywordTok{structure}\NormalTok{(ptspd)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## class : SpatialPointsDataFrame
## features : 10
## extent : -154.7469, 151.8235, -72.64904, 69.68905 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
## variables : 2
## names : Var1, Var2
## min values : -1.31199963817186, 1.29967134119943
## max values : 1.31409126373388, 9.85947532020509
\end{verbatim}
Our \textbf{datapt} is now the attribute table of \textbf{ptspd}. I can
efficiently access to the coordinates and the attributes tables using
``@'':
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ptspd}\OperatorTok{@}\NormalTok{data}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Var1 Var2
## 1 0.4423867 6.998069
## 2 0.6989734 9.859475
## 3 0.1653101 6.369589
## 4 0.4880717 9.215309
## 5 0.2906447 1.299671
## 6 0.6872198 8.584681
## 7 -1.3119996 6.364737
## 8 -0.4560925 5.838437
## 9 1.3140913 5.232988
## 10 -0.4708950 2.251813
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ptspd}\OperatorTok{@}\NormalTok{coords}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## x y
## [1,] -126.951509 -72.64904
## [2,] -18.450404 -47.97414
## [3,] -2.931689 -58.84770
## [4,] 9.235156 69.68905
## [5,] 82.904335 49.69026
## [6,] 33.599190 -37.76025
## [7,] -154.746863 33.46986
## [8,] -112.062220 -52.75116
## [9,] 151.823532 -46.35134
## [10,] 135.825774 -67.28474
\end{verbatim}
I plot \textbf{ptspd} and I specify that the size of points depends on
the second variable of the attribute table:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{plot}\NormalTok{(ptspd, }\DataTypeTok{pch=}\DecValTok{1}\NormalTok{, }\DataTypeTok{cex=}\NormalTok{ptspd}\OperatorTok{@}\NormalTok{data}\OperatorTok{$}\NormalTok{Var2)}
\end{Highlighting}
\end{Shaded}
\begin{figure}
\centering
\includegraphics{mapsR_files/figure-latex/unnamed-chunk-19-1.pdf}
\caption{A simple but customized plot of the
\emph{SpatialPointsDataframe} object \textbf{ptspd}.}
\end{figure}
Among the advantage of these spatial classes, there is the easiness of
the definition of proper subsets. For instance, you can create a new
\emph{SpatialPointsDataFrame} with points 1,2,4,5,7,8 of the previous as
follows:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ptspd2 <-ptspd[}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{2}\NormalTok{,}\DecValTok{4}\NormalTok{,}\DecValTok{5}\NormalTok{,}\DecValTok{7}\NormalTok{,}\DecValTok{8}\NormalTok{),]}
\CommentTok{# or ptspd2 <-ptspd[-c(3,6,9,10),]}
\end{Highlighting}
\end{Shaded}
Consistently, I get:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{summary}\NormalTok{(ptspd2)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Object of class SpatialPointsDataFrame
## Coordinates:
## min max
## x -154.74686 82.90433
## y -72.64904 69.68905
## Is projected: FALSE
## proj4string :
## [+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0]
## Number of points: 6
## Data attributes:
## Var1 Var2
## Min. :-1.31200 Min. :1.300
## 1st Qu.:-0.26941 1st Qu.:5.970
## Median : 0.36652 Median :6.681
## Mean : 0.02533 Mean :6.596
## 3rd Qu.: 0.47665 3rd Qu.:8.661
## Max. : 0.69897 Max. :9.859
\end{verbatim}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{ptspd2}\OperatorTok{@}\NormalTok{data}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Var1 Var2
## 1 0.4423867 6.998069
## 2 0.6989734 9.859475
## 4 0.4880717 9.215309
## 5 0.2906447 1.299671
## 7 -1.3119996 6.364737
## 8 -0.4560925 5.838437
\end{verbatim}
The main benefit of using such classes is to manipulate efficiently
spatial objects. There are a lot of functions already implemented and it
is straightforward to automate basic operations. For instance, you can
get all the distance between your points as follows:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# spDists(ptspd2)}
\end{Highlighting}
\end{Shaded}
\hypertarget{spatial-lines-and-polygons}{%
\section{Spatial Lines and Polygons}\label{spatial-lines-and-polygons}}
Creating either spatial points, either spatial lines or spatial polygons
are essentially the same approach. In the last section, I show how to
create spatial points, so, for lines and polygon, instead of points,
fundamental units are lists of lines or polygons. Therefore, the first
step is to define these new units thanks to two functions:
\textbf{Line()} and \textbf{Polygon()}. As for points, I re-use objects
defined in the first section. Our lines are split into two groups of
lines. First, I create empty lists:
\begin{Shaded}
\begin{Highlighting}[]
\CommentTok{# Two lists for the lines.}
\NormalTok{li1 <-}\StringTok{ }\KeywordTok{list}\NormalTok{()}
\NormalTok{li2 <-}\StringTok{ }\KeywordTok{list}\NormalTok{()}
\CommentTok{# One for the polygons (it could have been more!).}
\NormalTok{pol1 <-}\StringTok{ }\KeywordTok{list}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
Second, I fill the empty list using \textbf{Line()} and
\textbf{Polygon()} to create the fundamental units.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{li1[[}\DecValTok{1}\NormalTok{]]<-}\StringTok{ }\KeywordTok{Line}\NormalTok{(}\KeywordTok{cbind}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{1}\OperatorTok{:}\DecValTok{4}\NormalTok{], vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{1}\OperatorTok{:}\DecValTok{4}\NormalTok{]))}
\NormalTok{li1[[}\DecValTok{2}\NormalTok{]]<-}\StringTok{ }\KeywordTok{Line}\NormalTok{(}\KeywordTok{cbind}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{5}\OperatorTok{:}\DecValTok{6}\NormalTok{], vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{5}\OperatorTok{:}\DecValTok{6}\NormalTok{]))}
\NormalTok{##}
\NormalTok{li2[[}\DecValTok{1}\NormalTok{]]<-}\StringTok{ }\KeywordTok{Line}\NormalTok{(}\KeywordTok{cbind}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{7}\OperatorTok{:}\DecValTok{10}\NormalTok{], vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{7}\OperatorTok{:}\DecValTok{10}\NormalTok{]))}
\NormalTok{####}
\NormalTok{pol1[[}\DecValTok{1}\NormalTok{]] <-}\StringTok{ }\KeywordTok{Polygon}\NormalTok{(}\KeywordTok{cbind}\NormalTok{(}\KeywordTok{c}\NormalTok{(vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{1}\OperatorTok{:}\DecValTok{6}\NormalTok{],vec}\OperatorTok{$}\NormalTok{x[}\DecValTok{1}\NormalTok{]), }\KeywordTok{c}\NormalTok{(vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{1}\OperatorTok{:}\DecValTok{6}\NormalTok{],vec}\OperatorTok{$}\NormalTok{y[}\DecValTok{1}\NormalTok{])))}
\end{Highlighting}
\end{Shaded}
The next step transforms the previous lists into \emph{Lines} and
\emph{Polygons} object that must be identifies with an unique ID for the
next building steps.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{lin1 <-}\StringTok{ }\KeywordTok{Lines}\NormalTok{(li1,}\DataTypeTok{ID=}\DecValTok{1}\NormalTok{)}
\NormalTok{lin2 <-}\StringTok{ }\KeywordTok{Lines}\NormalTok{(li2,}\DataTypeTok{ID=}\DecValTok{2}\NormalTok{)}
\NormalTok{##}
\NormalTok{poly1 <-}\StringTok{ }\KeywordTok{Polygons}\NormalTok{(pol1, }\DataTypeTok{ID=}\DecValTok{1}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Then, I define object of class \emph{SpatialLines} and
\emph{SpatialPolygons}. They are respectively made of lists of lists of
lines and polygons together with a CRS.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{linsp <-}\StringTok{ }\KeywordTok{SpatialLines}\NormalTok{(}\KeywordTok{list}\NormalTok{(lin1,lin2),}
\DataTypeTok{proj4string=}\KeywordTok{CRS}\NormalTok{(}\StringTok{"+proj=longlat +datum=WGS84 +ellps=WGS84"}\NormalTok{))}
\CommentTok{#}
\NormalTok{polsp <-}\StringTok{ }\KeywordTok{SpatialPolygons}\NormalTok{(}\KeywordTok{list}\NormalTok{(poly1),}
\DataTypeTok{proj4string=}\KeywordTok{CRS}\NormalTok{(}\StringTok{"+proj=longlat +datum=WGS84 +ellps=WGS84"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
Finally, I add an attribute table to obtain objects of class
\emph{SpatialLinesDataFrame} and \emph{SpatialPolygonsDataFrame}.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{datalin<-}\KeywordTok{data.frame}\NormalTok{(}\DataTypeTok{var1=}\KeywordTok{runif}\NormalTok{(}\DecValTok{2}\NormalTok{), }\DataTypeTok{var2=}\KeywordTok{rnorm}\NormalTok{(}\DecValTok{2}\NormalTok{), }\DataTypeTok{var3=}\KeywordTok{rpois}\NormalTok{(}\DecValTok{2}\NormalTok{,}\DecValTok{10}\NormalTok{))}
\NormalTok{linspd <-}\StringTok{ }\KeywordTok{SpatialLinesDataFrame}\NormalTok{(linsp, }\DataTypeTok{data=}\KeywordTok{as.data.frame}\NormalTok{(datalin))}
\CommentTok{#}
\NormalTok{datapol<-}\KeywordTok{data.frame}\NormalTok{(}\DataTypeTok{var1=}\KeywordTok{runif}\NormalTok{(}\DecValTok{1}\NormalTok{), }\DataTypeTok{var2=}\KeywordTok{rnorm}\NormalTok{(}\DecValTok{1}\NormalTok{), }\DataTypeTok{var3=}\KeywordTok{rpois}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{10}\NormalTok{))}
\NormalTok{polspd <-}\StringTok{ }\KeywordTok{SpatialPolygonsDataFrame}\NormalTok{(polsp, }\DataTypeTok{data=}\NormalTok{datapol)}
\end{Highlighting}
\end{Shaded}
I suggest you look at these objects using \textbf{attributes()} or
\textbf{structures()} functions. To conclude the section, let's make a
quick plot:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{par}\NormalTok{(}\DataTypeTok{mfrow=}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{2}\NormalTok{), }\DataTypeTok{ann=}\OtherTok{FALSE}\NormalTok{, }\DataTypeTok{bty=}\StringTok{"l"}\NormalTok{)}
\KeywordTok{plot}\NormalTok{(linspd, }\DataTypeTok{col=}\KeywordTok{c}\NormalTok{(}\DecValTok{2}\NormalTok{,}\DecValTok{4}\NormalTok{))}
\KeywordTok{plot}\NormalTok{(polspd, }\DataTypeTok{col=}\DecValTok{4}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{figure}
\centering
\includegraphics{mapsR_files/figure-latex/unnamed-chunk-28-1.pdf}
\caption{\emph{SpatialLines} (on the left) and \emph{SpatialPolygons}
(on the right).}
\end{figure}
\hypertarget{spatial-grids}{%
\chapter{Spatial grids}\label{spatial-grids}}
The last classes of spatial defined in the ``sp'' package to be
presented are grids. Here, I do not present how to use a
\emph{SpatialPixel}. Rather, I shortly focus on \emph{SpatialGrid}
objects. Note that the next chapter is dedicated to raster objects which
are more used (as far as I know). First, you need to define a grid
topology using the \textbf{GridTopology()} function. You must specify
the following arguments:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
\emph{cellcentre.offset}: coordinates of the centre of the bottom-left
\item
\emph{cellsize}: a vector with the cell size in each dimension.
\item
\emph{cells.dim}: a vector with the number of cells in each dimension.
\end{enumerate}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{grd <-}\StringTok{ }\KeywordTok{GridTopology}\NormalTok{(}\DataTypeTok{cellcentre.offset=}\KeywordTok{c}\NormalTok{(}\OperatorTok{-}\FloatTok{179.5}\NormalTok{,}\OperatorTok{-}\FloatTok{89.5}\NormalTok{), }\DataTypeTok{cellsize=}\KeywordTok{c}\NormalTok{(}\DecValTok{1}\NormalTok{,}\DecValTok{1}\NormalTok{), }\DataTypeTok{cells.dim=}\KeywordTok{c}\NormalTok{(}\DecValTok{360}\NormalTok{,}\DecValTok{180}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
Then, I create a \emph{SpatialGrid} by adding a CRS:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{grdsp <-}\StringTok{ }\KeywordTok{SpatialGrid}\NormalTok{(grd, }\DataTypeTok{proj4string=}\KeywordTok{CRS}\NormalTok{(}\StringTok{"+proj=longlat +datum=WGS84 +ellps=WGS84"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
Finally, an attribute table is added to \textbf{grdsp} to obtain a
\emph{SpatialGridDataFrame} object called \textbf{grdspd}.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{var1 <-}\StringTok{ }\KeywordTok{runif}\NormalTok{(}\DecValTok{360}\OperatorTok{*}\DecValTok{180}\NormalTok{, }\DecValTok{0}\NormalTok{, }\DecValTok{10}\NormalTok{)}
\NormalTok{var2 <-}\StringTok{ }\KeywordTok{rnorm}\NormalTok{(}\DecValTok{360}\OperatorTok{*}\DecValTok{180}\NormalTok{, }\DecValTok{0}\NormalTok{, }\DecValTok{10}\NormalTok{)}
\NormalTok{datagd <-}\StringTok{ }\KeywordTok{data.frame}\NormalTok{(var1, var2)}
\CommentTok{#}
\NormalTok{grdspd <-}\StringTok{ }\KeywordTok{SpatialGridDataFrame}\NormalTok{(grdsp, }\DataTypeTok{data=}\NormalTok{datagd)}
\KeywordTok{par}\NormalTok{(}\DataTypeTok{mar=}\KeywordTok{c}\NormalTok{(}\DecValTok{4}\NormalTok{,}\DecValTok{4}\NormalTok{,}\DecValTok{1}\NormalTok{,}\DecValTok{1}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
I plot the new object and I add \textbf{ptspd} on it.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{image}\NormalTok{(grdspd)}
\KeywordTok{axis}\NormalTok{(}\DecValTok{1}\NormalTok{, }\KeywordTok{seq}\NormalTok{(}\OperatorTok{-}\DecValTok{180}\NormalTok{, }\DecValTok{180}\NormalTok{, }\DataTypeTok{by=}\DecValTok{20}\NormalTok{))}
\KeywordTok{axis}\NormalTok{(}\DecValTok{2}\NormalTok{, }\KeywordTok{seq}\NormalTok{(}\OperatorTok{-}\DecValTok{90}\NormalTok{, }\DecValTok{90}\NormalTok{, }\DataTypeTok{by=}\DecValTok{30}\NormalTok{))}
\KeywordTok{title}\NormalTok{(}\DataTypeTok{xlab=}\StringTok{"Longitude"}\NormalTok{, }\DataTypeTok{ylab=}\StringTok{"latitude"}\NormalTok{)}
\KeywordTok{plot}\NormalTok{(ptspd, }\DataTypeTok{add=}\OtherTok{TRUE}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{figure}
\centering
\includegraphics{mapsR_files/figure-latex/unnamed-chunk-32-1.pdf}
\caption{SpatialGrid plotted with the \emph{image} function together
with}
\end{figure}
\hypertarget{rasters}{%
\chapter{Rasters}\label{rasters}}
\hypertarget{package-raster}{%
\section{Package ``raster''}\label{package-raster}}
The
\href{http://cran.r-project.org/web/packages/raster/raster.pdf}{``raster''
package} defines classes, methods and functions for raster files. To the
best of my knowledge, I feel that people more often work with this
package rather than with the classes for grids defined in the ``sp''
package (but ``raster'' still imports ``sp''). I personally use ``sp''
package to manipulate vector files and ``raster'' for raster formats.
First, let's install and the package.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{install.packages}\NormalTok{(}\StringTok{"raster"}\NormalTok{)}
\KeywordTok{library}\NormalTok{(raster)}
\end{Highlighting}
\end{Shaded}
In the following sections below, I introduce the different classes
defined in ``raster''; that is \emph{RasterLayer}, \emph{RasterStack}
and \emph{RasterBrick}.
\hypertarget{rasterlayer}{%
\section{RasterLayer}\label{rasterlayer}}