This repository has been archived by the owner on Jan 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
05_Raster.knit.html
1355 lines (1262 loc) · 49.2 KB
/
05_Raster.knit.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<title>Introduction to Raster Package</title>
<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cosmo.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<style type="text/css">
/* padding for bootstrap navbar */
body {
padding-top: 51px;
padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar) */
.section h1 {
padding-top: 56px;
margin-top: -56px;
}
.section h2 {
padding-top: 56px;
margin-top: -56px;
}
.section h3 {
padding-top: 56px;
margin-top: -56px;
}
.section h4 {
padding-top: 56px;
margin-top: -56px;
}
.section h5 {
padding-top: 56px;
margin-top: -56px;
}
.section h6 {
padding-top: 56px;
margin-top: -56px;
}
</style>
<script>
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.parent().addClass('active');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
});
</script>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = true;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
padding-left: 25px;
text-indent: 0;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">GEO 503: Spatial Data Science</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="Syllabus.html">Syllabus</a>
</li>
<li>
<a href="Schedule.html">Schedule</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Content
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="CourseContent.html">About Course Content</a>
</li>
<li class="dropdown-header">Module 1: Introduction to R</li>
<li>
<a href="00_CourseIntroductionFrame.html">00 Course Introduction</a>
</li>
<li>
<a href="01_Rintro.html">01 First Steps</a>
</li>
<li>
<a href="02_graphics.html">02 Graphics</a>
</li>
<li>
<a href="03_DataWrangling.html">03 Data Wrangling</a>
</li>
<li>
<a href="03b_DataWrangling.html">03 Data Wrangling 2</a>
</li>
<li class="divider"></li>
<li class="dropdown-header">Module 2: Spatial Analyses</li>
<li>
<a href="04_Spatial_with_sf.html">04 Spatial Data with sf</a>
</li>
<li>
<a href="05_Raster.html">05 Spatial Raster Data</a>
</li>
<li class="divider"></li>
<li class="dropdown-header">Module 3: Advanced Programming</li>
<li>
<a href="06_CreatingWorkflows.html">06 Creating Workflows</a>
</li>
<li>
<a href="07_Reproducibile.html">07 Reproducible Research</a>
</li>
<li>
<a href="08_WeatherData.html">08 Weather Data Processing</a>
</li>
<li>
<a href="09_RemoteSensing_appeears.html">09 Satellite Data Processing</a>
</li>
<li>
<a href="11_ParallelProcessing.html">11 Parallel Processing</a>
</li>
<li>
<a href="12_DynamicVisualization.html">12 Dynamic Visualization</a>
</li>
<li>
<a href="13_SDM_Exercise.html">13 Species Distribution Modeling</a>
</li>
<li class="divider"></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Assignments
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="Tasklist.html">Task list</a>
</li>
<li>
<a href="DataCamp.html">DataCamp</a>
</li>
<li>
<a href="PackageIntro.html">Package Introduction</a>
</li>
<li>
<a href="Project.html">Final Project</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Resources
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="Provenance.html">Provenance</a>
</li>
<li>
<a href="Projects_2017.html">2017 Final Projects</a>
</li>
<li>
<a href="Resources.html">Resources</a>
</li>
<li>
<a href="GitSSHNotes.html">Setting up Github</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/adammwilson/RDataScience">
<span class="fa fa-github fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Introduction to Raster Package</h1>
</div>
<div class="extraswell">
<button data-toggle="collapse" class="btn btn-link" data-target="#pres">
View Presentation
</button>
<a href="presentations/PS_06_raster.html" target="_blank">Open presentation in a new tab</a>
<div id="pres" class="collapse">
<div class="embed-responsive embed-responsive-16by9">
<p><iframe class="embed-responsive-item" src="presentations/PS_06_raster.html" allowfullscreen></iframe> <em>Click on presentation and then use the space bar to advance to the next slide or escape key to show an overview.</em></p>
</div>
</div>
</div>
<div id="download" class="section level2">
<h2>Download</h2>
<table>
<thead>
<tr class="header">
<th align="center"><a href="scripts/05_Raster_nocomments.R"><i class="fas fa-code fa-2x" aria-hidden="true"></i><br> R Script</a></th>
<th align="center"><a href="scripts/05_Raster.R"><i class="fa fa-file-code-o fa-2x"></i> <br> Commented R Script</a></th>
<th align="center"><a href="scripts/05_Raster.Rmd"><i class="far fa-file-alt fa-2x"></i> <br> Rmd Script</a></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="libraries" class="section level2">
<h2>Libraries</h2>
<pre class="r"><code>library(dplyr)
library(tidyr)
library(sp)
library(ggplot2)
library(rgeos)
library(maptools)
# load data for this course
# devtools::install_github("adammwilson/DataScienceData")
library(DataScienceData)
# New libraries
library(raster)
library(rasterVis) #visualization library for raster</code></pre>
</div>
<div id="raster-package" class="section level1">
<h1>Raster Package</h1>
<div id="getdata" class="section level2">
<h2><code>getData()</code></h2>
<p>Raster package includes access to some useful (vector and raster) datasets with <code>getData()</code>:</p>
<ul>
<li>Elevation (SRTM 90m resolution raster)</li>
<li>World Climate (Tmin, Tmax, Precip, BioClim rasters)</li>
<li>Countries from CIA factsheet (vector!)</li>
<li>Global Administrative boundaries (vector!)</li>
</ul>
<p><code>getData()</code> steps for GADM:</p>
<ol style="list-style-type: decimal">
<li><em>Select Dataset</em>: ‘GADM’ returns the global administrative boundaries.</li>
<li><em>Select country</em>: Country name of the boundaries using its ISO A3 country code</li>
<li><em>Specify level</em>: Level of of administrative subdivision (0=country, 1=first level subdivision).</li>
</ol>
</div>
<div id="gadm-global-administrative-areas" class="section level2">
<h2>GADM: Global Administrative Areas</h2>
<p>Administrative areas in this database are countries and lower level subdivisions.</p>
<p><img src="05_assets/gadm25.png" alt="alt text" width="70%"></p>
<p>Divided by country (see website for full dataset). Explore country list:</p>
<pre class="r"><code>getData("ISO3")%>%
as.data.frame%>%
filter(NAME=="South Africa")</code></pre>
<pre><code>## ISO3 NAME
## 1 ZAF South Africa</code></pre>
<p>Download data for South Africa</p>
<pre class="r"><code>za=getData('GADM', country='ZAF', level=1)</code></pre>
<p>Or use the version in the DataScienceData</p>
<pre class="r"><code>data(southAfrica)
za=southAfrica # rename for convenience</code></pre>
<pre class="r"><code>plot(za)</code></pre>
<p>Danger: <code>plot()</code> works, but can be slow for complex polygons. If you want to speed it up, you can plot a simplified version as follows:</p>
<pre class="r"><code>za %>% gSimplify(0.01) %>% plot()</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-7-1.png" /><!-- --></p>
<div id="check-out-attribute-table" class="section level3">
<h3>Check out attribute table</h3>
<pre class="r"><code>za@data</code></pre>
<pre><code>## OBJECTID ID_0 ISO NAME_0 ID_1 NAME_1 HASC_1 CCN_1 CCA_1
## 1 1 211 ZAF South Africa 1 Eastern Cape ZA.EC NA EC
## 2 2 211 ZAF South Africa 2 Free State ZA.FS NA FS
## 3 3 211 ZAF South Africa 3 Gauteng ZA.GT NA GT
## 4 4 211 ZAF South Africa 4 KwaZulu-Natal ZA.NL NA KZN
## 5 5 211 ZAF South Africa 5 Limpopo ZA.NP NA LIM
## 6 6 211 ZAF South Africa 6 Mpumalanga ZA.MP NA MP
## 7 7 211 ZAF South Africa 7 North West ZA.NW NA NW
## 8 8 211 ZAF South Africa 8 Northern Cape ZA.NC NA NC
## 9 9 211 ZAF South Africa 9 Western Cape ZA.WC NA WC
## TYPE_1 ENGTYPE_1 NL_NAME_1
## 1 Provinsie Province
## 2 Provinsie Province
## 3 Provinsie Province
## 4 Provinsie Province
## 5 Provinsie Province
## 6 Provinsie Province
## 7 Provinsie Province
## 8 Provinsie Province
## 9 Provinsie Province
## VARNAME_1
## 1 Oos-Kaap
## 2 Orange Free State|Vrystaat
## 3 Pretoria/Witwatersrand/Vaal
## 4 Natal and Zululand
## 5 Noordelike Provinsie|Northern Transvaal|Northern Province
## 6 Eastern Transvaal
## 7 North-West|Noordwes
## 8 Noord-Kaap
## 9 Wes-Kaap</code></pre>
<p>Plot a subsetted region:</p>
<pre class="r"><code>subset(za,NAME_1=="Western Cape") %>% gSimplify(0.01) %>%
plot()</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-9-1.png" /><!-- --></p>
<div class="well">
<h2 id="your-turn">Your turn</h2>
<p>Use the method above to download and plot the boundaries for a country of your choice.</p>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo1">
Show Solution
</button>
<div id="demo1" class="collapse">
<pre class="r"><code>getData("ISO3")%>%
as.data.frame%>%
filter(NAME=="Tunisia")</code></pre>
<pre><code>## ISO3 NAME
## 1 TUN Tunisia</code></pre>
<pre class="r"><code>country=getData('GADM', country='TUN', level=2)
country%>%
gSimplify(0.01)%>%
plot()</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-10-1.png" /><!-- --></p>
</div>
</div>
</div>
</div>
</div>
<div id="raster-data" class="section level1">
<h1>Raster Data</h1>
<div id="raster-introduction" class="section level2">
<h2>Raster introduction</h2>
<p>Spatial data structure dividing region (‘grid’) into rectangles (’cells’ or ’pixels’) storing one or more values each.</p>
<p><small> Some examples from the <a href="http://cran.r-project.org/web/packages/raster/vignettes/Raster.pdf">Raster vignette</a> by Robert J. Hijmans. </small></p>
<ul>
<li><code>rasterLayer</code>: 1 band</li>
<li><code>rasterStack</code>: Multiple Bands</li>
<li><code>rasterBrick</code>: Multiple Bands of <em>same</em> thing.</li>
</ul>
<pre class="r"><code>x <- raster()
x</code></pre>
<pre><code>## class : RasterLayer
## dimensions : 180, 360, 64800 (nrow, ncol, ncell)
## resolution : 1, 1 (x, y)
## extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0</code></pre>
<pre class="r"><code>str(x)</code></pre>
<pre><code>## Formal class 'RasterLayer' [package "raster"] with 12 slots
## ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
## .. .. ..@ name : chr ""
## .. .. ..@ datanotation: chr "FLT4S"
## .. .. ..@ byteorder : chr "little"
## .. .. ..@ nodatavalue : num -Inf
## .. .. ..@ NAchanged : logi FALSE
## .. .. ..@ nbands : int 1
## .. .. ..@ bandorder : chr "BIL"
## .. .. ..@ offset : int 0
## .. .. ..@ toptobottom : logi TRUE
## .. .. ..@ blockrows : int 0
## .. .. ..@ blockcols : int 0
## .. .. ..@ driver : chr ""
## .. .. ..@ open : logi FALSE
## ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
## .. .. ..@ values : logi(0)
## .. .. ..@ offset : num 0
## .. .. ..@ gain : num 1
## .. .. ..@ inmemory : logi FALSE
## .. .. ..@ fromdisk : logi FALSE
## .. .. ..@ isfactor : logi FALSE
## .. .. ..@ attributes: list()
## .. .. ..@ haveminmax: logi FALSE
## .. .. ..@ min : num Inf
## .. .. ..@ max : num -Inf
## .. .. ..@ band : int 1
## .. .. ..@ unit : chr ""
## .. .. ..@ names : chr ""
## ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
## .. .. ..@ type : chr(0)
## .. .. ..@ values : logi(0)
## .. .. ..@ color : logi(0)
## .. .. ..@ names : logi(0)
## .. .. ..@ colortable: logi(0)
## ..@ title : chr(0)
## ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
## .. .. ..@ xmin: num -180
## .. .. ..@ xmax: num 180
## .. .. ..@ ymin: num -90
## .. .. ..@ ymax: num 90
## ..@ rotated : logi FALSE
## ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
## .. .. ..@ geotrans: num(0)
## .. .. ..@ transfun:function ()
## ..@ ncols : int 360
## ..@ nrows : int 180
## ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
## .. .. ..@ projargs: chr "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
## ..@ history : list()
## ..@ z : list()</code></pre>
<pre class="r"><code>x <- raster(ncol=36, nrow=18, xmn=-1000, xmx=1000, ymn=-100, ymx=900)
res(x)</code></pre>
<pre><code>## [1] 55.55556 55.55556</code></pre>
<pre class="r"><code>res(x) <- 100
res(x)</code></pre>
<pre><code>## [1] 100 100</code></pre>
<pre class="r"><code>ncol(x)</code></pre>
<pre><code>## [1] 20</code></pre>
<pre class="r"><code># change the numer of columns (affects resolution)
ncol(x) <- 18
ncol(x)</code></pre>
<pre><code>## [1] 18</code></pre>
<pre class="r"><code>res(x)</code></pre>
<pre><code>## [1] 111.1111 100.0000</code></pre>
</div>
<div id="raster-data-storage" class="section level2">
<h2>Raster data storage</h2>
<pre class="r"><code>r <- raster(ncol=10, nrow=10)
ncell(r)</code></pre>
<pre><code>## [1] 100</code></pre>
<p>But it is an empty raster</p>
<pre class="r"><code>hasValues(r)</code></pre>
<pre><code>## [1] FALSE</code></pre>
<p>Use <code>values()</code> function:</p>
<pre class="r"><code>values(r) <- 1:ncell(r)
hasValues(r)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>values(r)[1:10]</code></pre>
<pre><code>## [1] 1 2 3 4 5 6 7 8 9 10</code></pre>
<div class="well">
<h2 id="your-turn-1">Your turn</h2>
<p>Create and then plot a new raster with:</p>
<ol style="list-style-type: decimal">
<li>100 rows</li>
<li>50 columns</li>
<li>Fill it with random values (<code>rnorm()</code>)</li>
</ol>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo2">
Show Solution
</button>
<div id="demo2" class="collapse">
<pre class="r"><code>x=raster(nrow=100,ncol=50,vals=rnorm(100*50))
# OR
x= raster(nrow=100,ncol=50)
values(x)= rnorm(5000)
plot(x)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-18-1.png" /><!-- --></p>
</div>
</div>
<p>Raster memory usage</p>
<pre class="r"><code>inMemory(r)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<blockquote>
<p>You can change the memory options using the <code>maxmemory</code> option in <code>rasterOptions()</code></p>
</blockquote>
</div>
<div id="raster-plotting" class="section level2">
<h2>Raster Plotting</h2>
<p>Plotting is easy (but slow) with <code>plot</code>.</p>
<pre class="r"><code>plot(r, main='Raster with 100 cells')</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-20-1.png" /><!-- --></p>
<div id="ggplot-and-rastervis" class="section level3">
<h3>ggplot and rasterVis</h3>
<p>rasterVis package has <code>gplot()</code> for plotting raster data in the <code>ggplot()</code> framework.</p>
<pre class="r"><code>gplot(r,maxpixels=50000)+
geom_raster(aes(fill=value))</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-21-1.png" /><!-- --></p>
<p>Adjust <code>maxpixels</code> for faster plotting of large datasets.</p>
<pre class="r"><code>gplot(r,maxpixels=10)+
geom_raster(aes(fill=value))</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-22-1.png" /><!-- --></p>
<p>Can use all the <code>ggplot</code> color ramps, etc.</p>
<pre class="r"><code>gplot(r)+geom_raster(aes(fill=value))+
scale_fill_distiller(palette="OrRd")</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-23-1.png" /><!-- --></p>
</div>
</div>
<div id="spatial-projections" class="section level2">
<h2>Spatial Projections</h2>
<p>Raster package uses standard <a href="http://www.spatialreference.org">coordinate reference system (CRS)</a>.</p>
<p>For example, see the projection format for the <a href="http://www.spatialreference.org/ref/epsg/4326/"><em>standard</em> WGS84</a>.</p>
<pre class="r"><code>projection(r)</code></pre>
<pre><code>## [1] "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"</code></pre>
</div>
<div id="warping-rasters" class="section level2">
<h2>Warping rasters</h2>
<p>Use <code>projectRaster()</code> to <em>warp</em> to a different projection.</p>
<p><code>method=</code> <code>ngb</code> (for categorical) or <code>bilinear</code> (continuous)</p>
<pre class="r"><code>r2=projectRaster(r,crs="+proj=sinu +lon_0=0",method = "ngb")</code></pre>
<pre><code>## Warning in rgdal::rawTransform(projto_int, projfrom, nrow(xy), xy[, 1], :
## 48 projected point(s) not finite</code></pre>
<pre class="r"><code>par(mfrow=c(1,2));plot(r);plot(r2)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-25-1.png" /><!-- --></p>
</div>
</div>
<div id="worldclim" class="section level1">
<h1>WorldClim</h1>
<div id="overview-of-worldclim" class="section level2">
<h2>Overview of WorldClim</h2>
<p>Mean monthly climate and derived variables interpolated from weather stations on a 30 arc-second (~1km) grid. See <a href="http://www.worldclim.org/methods">worldclim.org</a></p>
</div>
<div id="bioclim-variables" class="section level2">
<h2>Bioclim variables</h2>
<p><small></p>
<table>
<thead>
<tr class="header">
<th>Varia</th>
<th>ble Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>BIO1</td>
<td>Annual Mean Temperature</td>
</tr>
<tr class="even">
<td>BIO2</td>
<td>Mean Diurnal Range (Mean of monthly (max temp – min temp))</td>
</tr>
<tr class="odd">
<td>BIO3</td>
<td>Isothermality (BIO2/BIO7) (* 100)</td>
</tr>
<tr class="even">
<td>BIO4</td>
<td>Temperature Seasonality (standard deviation *100)</td>
</tr>
<tr class="odd">
<td>BIO5</td>
<td>Max Temperature of Warmest Month</td>
</tr>
<tr class="even">
<td>BIO6</td>
<td>Min Temperature of Coldest Month</td>
</tr>
<tr class="odd">
<td>BIO7</td>
<td>Temperature Annual Range (BIO5-BIO6)</td>
</tr>
<tr class="even">
<td>BIO8</td>
<td>Mean Temperature of Wettest Quarter</td>
</tr>
<tr class="odd">
<td>BIO9</td>
<td>Mean Temperature of Driest Quarter</td>
</tr>
<tr class="even">
<td>BIO10</td>
<td>Mean Temperature of Warmest Quarter</td>
</tr>
<tr class="odd">
<td>BIO11</td>
<td>Mean Temperature of Coldest Quarter</td>
</tr>
<tr class="even">
<td>BIO12</td>
<td>Annual Precipitation</td>
</tr>
<tr class="odd">
<td>BIO13</td>
<td>Precipitation of Wettest Month</td>
</tr>
<tr class="even">
<td>BIO14</td>
<td>Precipitation of Driest Month</td>
</tr>
<tr class="odd">
<td>BIO15</td>
<td>Precipitation Seasonality (Coefficient of Variation)</td>
</tr>
<tr class="even">
<td>BIO16</td>
<td>Precipitation of Wettest Quarter</td>
</tr>
<tr class="odd">
<td>BIO17</td>
<td>Precipitation of Driest Quarter</td>
</tr>
<tr class="even">
<td>BIO18</td>
<td>Precipitation of Warmest Quarter</td>
</tr>
<tr class="odd">
<td>BIO19</td>
<td>Precipitation of Coldest Quarter</td>
</tr>
</tbody>
</table>
<p></small></p>
</div>
<div id="download-climate-data" class="section level2">
<h2>Download climate data</h2>
<p>Download the data:</p>
<pre class="r"><code>clim=raster::getData('worldclim', var='bio', res=10) </code></pre>
<p><code>res</code> is resolution (0.5, 2.5, 5, and 10 minutes of a degree)</p>
<p>Instead of downloading the full dataset, we’ll use the copy in the <code>DataScienceData</code> package:</p>
<pre class="r"><code>data(worldclim)
#rename for convenience
clim=worldclim</code></pre>
<div id="gain-and-offset" class="section level3">
<h3>Gain and Offset</h3>
<pre class="r"><code>clim</code></pre>
<pre><code>## class : RasterStack
## dimensions : 900, 2160, 1944000, 19 (nrow, ncol, ncell, nlayers)
## resolution : 0.1666667, 0.1666667 (x, y)
## extent : -180, 180, -60, 90 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
## names : bio1, bio2, bio3, bio4, bio5, bio6, bio7, bio8, bio9, bio10, bio11, bio12, bio13, bio14, bio15, ...
## min values : -269, 9, 8, 72, -59, -547, 53, -251, -450, -97, -488, 0, 0, 0, 0, ...
## max values : 314, 211, 95, 22673, 489, 258, 725, 375, 364, 380, 289, 9916, 2088, 652, 261, ...</code></pre>
<p>Note the min/max of the raster. What are the units? Always check metadata, the <a href="http://www.worldclim.org/formats">WorldClim temperature dataset</a> has a <code>gain</code> of 0.1, meaning that it must be multipled by 0.1 to convert back to degrees Celsius. We’ll set the temperature variables (see table above) to 0.1 and leave the others at 1.</p>
<pre class="r"><code>gain(clim)=c(rep(0.1,11),rep(1,7))</code></pre>
</div>
<div id="plot-with-plot" class="section level3">
<h3>Plot with <code>plot()</code></h3>
<pre class="r"><code>plot(clim)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-30-1.png" /><!-- --></p>
</div>
</div>
<div id="faceting-in-ggplot" class="section level2">
<h2>Faceting in ggplot</h2>
<p>Or use <code>rasterVis</code> methods with gplot</p>
<pre class="r"><code>gplot(clim[[13:19]])+geom_raster(aes(fill=value))+
facet_wrap(~variable)+
scale_fill_gradientn(colours=c("brown","red","yellow","darkgreen","green"),trans="log10")+
coord_equal()</code></pre>
<pre><code>## Warning: Transformation introduced infinite values in discrete y-axis</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-31-1.png" /><!-- --></p>
<p>Let’s dig a little deeper into the data object:</p>
<pre class="r"><code>## is it held in RAM?
inMemory(clim)</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre class="r"><code>## How big is it?
object.size(clim)</code></pre>
<pre><code>## 295722384 bytes</code></pre>
<pre class="r"><code>## can we work with it directly in RAM?
canProcessInMemory(clim)</code></pre>
<pre><code>## [1] TRUE</code></pre>
</div>
<div id="subsetting-and-spatial-cropping" class="section level2">
<h2>Subsetting and spatial cropping</h2>
<p>Use <code>[[1:3]]</code> to select raster layers from raster stack.</p>
<pre class="r"><code>## crop to a latitude/longitude box
r1 <- raster::crop(clim[[1]], extent(10,35,-35,-20))
## Crop using a Spatial polygon
r1 <- raster::crop(clim[[1]], bbox(za))</code></pre>
<pre class="r"><code>r1</code></pre>
<pre><code>## class : RasterLayer
## dimensions : 76, 98, 7448 (nrow, ncol, ncell)
## resolution : 0.1666667, 0.1666667 (x, y)
## extent : 16.5, 32.83333, -34.83333, -22.16667 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
## data source : in memory
## names : bio1
## values : 5.8, 24.6 (min, max)</code></pre>
<pre class="r"><code>plot(r1)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-34-1.png" /><!-- --></p>
</div>
<div id="spatial-aggregation" class="section level2">
<h2>Spatial aggregation</h2>
<pre class="r"><code>## aggregate using a function
aggregate(r1, 3, fun=mean) %>%
plot()</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-35-1.png" /><!-- --></p>
<div class="well">
<h2 id="your-turn-2">Your turn</h2>
<p>Create a new raster by aggregating to the minimum (<code>min</code>) value of <code>r1</code> within a 10 pixel window</p>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo3">
Show Solution
</button>
<div id="demo3" class="collapse">
<pre class="r"><code>aggregate(r1, 10, fun=min) %>%
plot()</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-36-1.png" /><!-- --></p>
</div>
</div>
</div>
<div id="focal-moving-window" class="section level2">
<h2>Focal (“moving window”)</h2>
<pre class="r"><code>## apply a function over a moving window
focal(r1, w=matrix(1,3,3), fun=mean) %>%
plot()</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-37-1.png" /><!-- --></p>
<pre class="r"><code>## apply a function over a moving window
rf_min <- focal(r1, w=matrix(1,11,11), fun=min)
rf_max <- focal(r1, w=matrix(1,11,11), fun=max)
rf_range=rf_max-rf_min
## or do it all at once
range2=function(x,na.rm=F) {
max(x,na.rm)-min(x,na.rm)
}
rf_range2 <- focal(r1, w=matrix(1,11,11), fun=range2)
plot(rf_range)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-38-1.png" /><!-- --></p>
<pre class="r"><code>plot(rf_range2)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-38-2.png" /><!-- --></p>
<div class="well">
<h2 id="your-turn-3">Your turn</h2>
<p>Plot the focal standard deviation of <code>r1</code> over a 3x3 window.</p>
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo4">
Show Solution
</button>
<div id="demo4" class="collapse">
<pre class="r"><code>focal(r1,w=matrix(1,3,3),fun=sd)%>%
plot()</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-39-1.png" /><!-- --></p>
</div>
</div>
</div>
<div id="raster-calculations" class="section level2">
<h2>Raster calculations</h2>
<p>the <code>raster</code> package has many options for <em>raster algebra</em>, including <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, logical operators such as <code>></code>, <code>>=</code>, <code><</code>, <code>==</code>, <code>!</code> and functions such as <code>abs</code>, <code>round</code>, <code>ceiling</code>, <code>floor</code>, <code>trunc</code>, <code>sqrt</code>, <code>log</code>, <code>log10</code>, <code>exp</code>, <code>cos</code>, <code>sin</code>, <code>max</code>, <code>min</code>, <code>range</code>, <code>prod</code>, <code>sum</code>, <code>any</code>, <code>all</code>.</p>
<p>So, for example, you can</p>
<pre class="r"><code>cellStats(r1,range)</code></pre>
<pre><code>## [1] 5.8 24.6</code></pre>
<pre class="r"><code>## add 10
s = r1 + 10
cellStats(s,range)</code></pre>
<pre><code>## [1] 15.8 34.6</code></pre>
<pre class="r"><code>## take the square root
s = sqrt(r1)
cellStats(s,range)</code></pre>
<pre><code>## [1] 2.408319 4.959839</code></pre>
<pre class="r"><code># round values
r = round(r1)
cellStats(r,range)</code></pre>
<pre><code>## [1] 6 25</code></pre>
<pre class="r"><code># find cells with values less than 15 degrees C
r = r1 < 15
plot(r)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-41-1.png" /><!-- --></p>
<div id="apply-algebraic-functions" class="section level3">
<h3>Apply algebraic functions</h3>
<pre class="r"><code># multiply s times r and add 5
s = s * r1 + 5
cellStats(s,range)</code></pre>
<pre><code>## [1] 18.96825 127.01203</code></pre>
</div>
</div>
<div id="extracting-raster-data" class="section level2">
<h2>Extracting Raster Data</h2>
<ul>
<li>points</li>
<li>lines</li>
<li>polygons</li>
<li>extent (rectangle)</li>
<li>cell numbers</li>
</ul>
<p>Extract all intersecting values OR apply a summarizing function with <code>fun</code>.</p>
<div id="point-data" class="section level3">
<h3>Point data</h3>
<p><code>sampleRandom()</code> generates random points and automatically extracts the raster values for those points. Also check out <code>?sampleStratified</code> and <code>sampleRegular()</code>.</p>
<p>Generate 100 random points and the associated climate variables at those points.</p>
<pre class="r"><code>## define a new dataset of points to play with
pts=sampleRandom(clim,100,xy=T,sp=T)
plot(pts);axis(1);axis(2)</code></pre>
<p><img src="05_Raster_files/figure-html/unnamed-chunk-43-1.png" /><!-- --></p>
</div>
<div id="extract-data-using-a-spatialpoints-object" class="section level3">
<h3>Extract data using a <code>SpatialPoints</code> object</h3>
<p>Often you will have some locations (points) for which you want data from a raster* object. You can use the <code>extract</code> function here with the <code>pts</code> object (we’ll pretend it’s a new point dataset for which you want climate variables).</p>
<pre class="r"><code>pts_data=raster::extract(clim[[1:4]],pts,df=T)
head(pts_data)</code></pre>
<pre><code>## ID bio1 bio2 bio3 bio4
## 1 1 20.8 15.6 5.5 448.1
## 2 2 26.4 10.0 8.6 30.0
## 3 3 7.8 9.5 3.8 537.8
## 4 4 17.6 17.3 4.4 698.6
## 5 5 -10.6 8.4 1.6 1493.1
## 6 6 9.2 9.3 2.6 935.6</code></pre>