-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathR-GIS_tutorial.Rmd
More file actions
1066 lines (690 loc) · 24.1 KB
/
R-GIS_tutorial.Rmd
File metadata and controls
1066 lines (690 loc) · 24.1 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
Spatial data in R: Using R as a GIS
========================================================
A tutorial to perform basic operations with spatial data in R, such as importing and exporting data (both vectorial and raster), plotting, analysing and making maps.
[Francisco Rodriguez-Sanchez](http://sites.google.com/site/rodriguezsanchezf)
v 2.2
27-01-2015
Licence: [CC BY 4.0](http://creativecommons.org/licenses/by/4.0/)
Check out code and latest version at [GitHub](https://github.com/Pakillo/R-GIS-tutorial/blob/master/R-GIS_tutorial.md)
<br>
<br>
<br>
CONTENTS <a name="contents"></a>
=========
<br>
<br>
[1. INTRODUCTION](#intro)
<br>
<br>
[2. GENERIC MAPPING](#mapping)
<br>
* [Retrieving base maps from Google with `gmap` function in package `dismo`](#gmap)
* [`RgoogleMaps`: Map your data onto Google Map tiles](#rgooglemaps)
* [`googleVis`: visualise data in a web browser using Google Visualisation API](#googlevis)
* [`RWorldMap`: mapping global data](#rworldmap)
<br>
<br>
[3. SPATIAL VECTOR DATA (points, lines, polygons)](#vector)
<br>
* [Example dataset: retrieve point occurrence data from GBIF](#gbif)
* [Making data 'spatial'](#spatial)
* [Define spatial projection](#projection)
* [Quickly plotting point data on a map](#plot)
* [Subsetting and mapping again](#subset)
* [Mapping vectorial data (points, polygons, polylines)](#mapvector)
* [Drawing polygons and polylines (e.g. for digitising)](#digitise)
* [Converting between formats, reading in, and saving spatial vector data](#iovec)
* [Changing projection of spatial vector data](#changeproj)
<br>
<br>
[4. USING RASTER (GRID) DATA](#raster)
<br>
* [Downloading raster climate data from internet](#getdata)
* [Loading a raster layer](#loadraster)
* [Creating a raster stack](#rasterstack)
* [Raster bricks](#rasterbrick)
* [Crop rasters](#cropraster)
* [Define spatial projection of the rasters](#projectionraster)
* [Changing projection](#changeprojraster)
* [Plotting raster data](#plotraster)
* [Spatial autocorrelation](#autocorrelation)
* [Extract values from raster](#extract)
* [Rasterize vector data (points, lines or polygons)](#rasterize)
* [Changing raster resolution](#resolution)
* [Spline interpolation](#interpolation)
* [Setting all rasters to the same extent, projection and resolution all in one](#spatialsync)
* [Elevations, slope, aspect, etc](#elevation)
* [Saving and exporting raster data](#saveraster)
<br>
<br>
[5. SPATIAL STATISTICS](#spatstats)
<br>
* [Point pattern analysis](#pointpatterns)
* [Geostatistics](#geostatistics)
<br>
<br>
[6. INTERACTING WITH OTHER GIS](#othergis)
<br>
<br>
[7. OTHER USEFUL PACKAGES](#otherpackages)
<br>
<br>
[8. TO LEARN MORE](#tolearnmore)
<br>
<br>
<br>
<br>
1. INTRODUCTION <a name="intro"></a>
===============
<br>
R is great not only for doing statistics, but also for many other tasks, including GIS analysis and working with spatial data. For instance, R is capable of doing wonderful maps such as [this](http://spatialanalysis.co.uk/wp-content/uploads/2012/02/bike_ggplot.png) or [this](http://oscarperpinan.github.io/spacetime-vis/images/airMadrid_stamen.png). In this tutorial I will show some basic GIS functionality in R.
#### Basic packages
```{r message=FALSE}
library(sp) # classes for spatial data
library(raster) # grids, rasters
library(rasterVis) # raster visualisation
library(maptools)
library(rgeos)
# and their dependencies
```
There are many other useful packages, e.g. check [CRAN Spatial Task View](http://cran.r-project.org/web/views/Spatial.html). Some of them will be used below.
<br>
[Back to Contents](#contents)
<br>
<br>
<br>
<br>
2. GENERIC MAPPING <a name="mapping"></a>
==================
<br>
Retrieving base maps from Google with `gmap` function in package `dismo` <a name="gmap"></a>
------------------------------------------------------------------------
Some examples:
Getting maps for countries:
```{r gmap1, message=FALSE}
library(dismo)
mymap <- gmap("France") # choose whatever country
plot(mymap)
```
Choose map type:
```{r gmap2, message=FALSE}
mymap <- gmap("France", type="satellite")
plot(mymap)
```
Choose zoom level:
```{r gmap3, message=FALSE}
mymap <- gmap("France", type="satellite", exp=3)
plot(mymap)
```
Save the map as a file in your working directory for future use
```{r message=FALSE}
mymap <- gmap("France", type="satellite", filename="France.gmap")
```
Now get a map for a region drawn at hand
```{r eval=FALSE}
mymap <- gmap("Europe")
plot(mymap)
select.area <- drawExtent()
# now click 2 times on the map to select your region
mymap <- gmap(select.area)
plot(mymap)
# See ?gmap for many other possibilities
```
<br>
<br>
`RgoogleMaps`: Map your data onto Google Map tiles <a name="rgooglemaps"></a>
------------------------------------------------
```{r message=FALSE, results='hide'}
library(RgoogleMaps)
```
Get base maps from Google (a file will be saved in your working directory)
```{r message=FALSE, results='hide'}
newmap <- GetMap(center=c(36.7,-5.9), zoom =10, destfile = "newmap.png", maptype = "satellite")
# Now using bounding box instead of center coordinates:
newmap2 <- GetMap.bbox(lonR=c(-5, -6), latR=c(36, 37), destfile = "newmap2.png", maptype="terrain")
# Try different maptypes
newmap3 <- GetMap.bbox(lonR=c(-5, -6), latR=c(36, 37), destfile = "newmap3.png", maptype="satellite")
```
Now plot data onto these maps, e.g. these 3 points
```{r}
PlotOnStaticMap(lat = c(36.3, 35.8, 36.4), lon = c(-5.5, -5.6, -5.8), zoom= 10,
cex=4, pch= 19, col="red", FUN = points, add=F)
```
<br>
<br>
`googleVis`: visualise data in a web browser using Google Visualisation API <a name="googlevis"></a>
---------------------------------------------------------------------------
```{r message=FALSE}
library(googleVis)
```
Run `demo(googleVis)` to see all the possibilities
```{r setOptions, echo=FALSE}
op <- options(gvis.plot.tag = "chart")
# necessary so that googleVis works with knitr, see http://lamages.blogspot.co.uk/2012/10/googlevis-032-is-released-better.html
```
<br>
### Example: plot country-level data
```{r results='asis', tidy=FALSE, eval=TRUE}
data(Exports) # a simple data frame
Geo <- gvisGeoMap(Exports, locationvar="Country", numvar="Profit",
options=list(height=400, dataMode='regions'))
plot(Geo)
```
Using `print(Geo)` we can get the HTML code to embed the map in a web page!
<br>
### Example: Plotting point data onto a google map (internet)
```{r results='asis', tidy=FALSE, eval=TRUE}
data(Andrew)
M1 <- gvisMap(Andrew, "LatLong", "Tip",
options=list(showTip=TRUE, showLine=F, enableScrollWheel=TRUE,
mapType='satellite', useMapTypeControl=TRUE, width=800,height=400))
plot(M1)
```
<br>
<br>
`RWorldMap`: mapping global data <a name="rworldmap"></a>
--------------------------------
Some examples
```{r message=FALSE, warning=FALSE}
library(rworldmap)
newmap <- getMap(resolution="coarse") # different resolutions available
plot(newmap)
```
```{r message=FALSE}
mapCountryData()
```
```{r message=FALSE}
mapCountryData(mapRegion="europe")
```
```{r message=FALSE}
mapGriddedData()
```
```{r message=FALSE}
mapGriddedData(mapRegion="europe")
```
<br>
[Back to Contents](#contents)
<br>
<br>
<br>
<br>
<br>
3. SPATIAL VECTOR DATA (points, lines, polygons) <a name="vector"></a>
================================================
<br>
<br>
### Example dataset: retrieve point occurrence data from GBIF <a name="gbif"></a>
Let's create an example dataset: retrieve occurrence data
for the laurel tree (Laurus nobilis) from the
[Global Biodiversity Information Facility (GBIF)](http://gbif.org)
```{r message=FALSE}
library(dismo) # check also the nice "rgbif" package!
laurus <- gbif("Laurus", "nobilis")
# get data frame with spatial coordinates (points)
locs <- subset(laurus, select=c("country", "lat", "lon"))
head(locs) # a simple data frame with coordinates
# Discard data with errors in coordinates:
locs <- subset(locs, locs$lat<90)
```
<br>
### Making data 'spatial' <a name="spatial"></a>
So we have got a simple dataframe containing spatial coordinates.
Let's make these data explicitly *spatial*
```{r}
coordinates(locs) <- c("lon", "lat") # set spatial coordinates
plot(locs)
```
### Define spatial projection <a name="projection"></a>
Important: define geographical projection.
Consult the appropriate PROJ.4 description here:
[http://www.spatialreference.org/](http://www.spatialreference.org/)
```{r}
crs.geo <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") # geographical, datum WGS84
proj4string(locs) <- crs.geo # define projection system of our data
summary(locs)
```
<br>
### Quickly plotting point data on a map <a name="plot"></a>
```{r}
plot(locs, pch=20, col="steelblue")
library(rworldmap)
# library rworldmap provides different types of global maps, e.g:
data(coastsCoarse)
data(countriesLow)
plot(coastsCoarse, add=T)
```
### Subsetting and mapping again <a name="subset"></a>
```{r}
table(locs$country) # see localities of Laurus nobilis by country
locs.gb <- subset(locs, locs$country=="United Kingdom") # select only locs in UK
plot(locs.gb, pch=20, cex=2, col="steelblue")
title("Laurus nobilis occurrences in UK")
plot(countriesLow, add=T)
summary(locs.gb)
```
<br>
Mapping vectorial data (points, polygons, polylines) <a name="mapvector"></a>
---------------------------------------------------------------------
<br>
### Mapping vectorial data using `gmap` from `dismo`
```{r}
gbmap <- gmap(locs.gb, type="satellite")
locs.gb.merc <- Mercator(locs.gb) # Google Maps are in Mercator projection.
# This function projects the points to that projection to enable mapping
plot(gbmap)
points(locs.gb.merc, pch=20, col="red")
```
<br>
### Mapping vectorial data with `RgoogleMaps`
```{r message=FALSE}
require(RgoogleMaps)
locs.gb.coords <- as.data.frame(coordinates(locs.gb)) # retrieves coordinates
# (1st column for longitude, 2nd column for latitude)
PlotOnStaticMap(lat = locs.gb.coords$lat, lon = locs.gb.coords$lon,
zoom= 5, cex=1.4, pch= 19, col="red", FUN = points, add=F)
```
Download base map from Google Maps and plot onto it
```{r message=FALSE}
map.lim <- qbbox (locs.gb.coords$lat, locs.gb.coords$lon, TYPE="all") # define region
# of interest (bounding box)
mymap <- GetMap.bbox(map.lim$lonR, map.lim$latR, destfile = "gmap.png", maptype="satellite")
# see the file in the wd
PlotOnStaticMap(mymap, lat = locs.gb.coords$lat, lon = locs.gb.coords$lon,
zoom= NULL, cex=1.3, pch= 19, col="red", FUN = points, add=F)
```
<br>
<br>
Using different background (base map)
```{r message=FALSE}
mymap <- GetMap.bbox(map.lim$lonR, map.lim$latR, destfile = "gmap.png", maptype="hybrid")
PlotOnStaticMap(mymap, lat = locs.gb.coords$lat, lon = locs.gb.coords$lon,
zoom= NULL, cex=1.3, pch= 19, col="red", FUN = points, add=F)
```
<br>
<br>
### Map vectorial data with `googleVis` (internet)
```{r results='asis', tidy=FALSE, eval=TRUE}
points.gb <- as.data.frame(locs.gb)
points.gb$latlon <- paste(points.gb$lat, points.gb$lon, sep=":")
map.gb <- gvisMap(points.gb, locationvar="latlon", tipvar="country",
options = list(showTip=T, showLine=F, enableScrollWheel=TRUE,
useMapTypeControl=T, width=1400,height=800))
plot(map.gb)
#print(map.gb) # get HTML suitable for a webpage
```
<br>
<br>
<br>
### Drawing polygons and polylines (e.g. for digitising) <a name="digitise"></a>
```{r eval=FALSE}
plot(gbmap)
mypolygon <- drawPoly() # click on the map to draw a polygon and press ESC when finished
summary(mypolygon) # now you have a spatial polygon! Easy, isn't it?
```
<br>
<br>
<br>
<br>
Converting between formats, reading in, and saving spatial vector data <a name="iovec"></a>
-------------------------------------------------------------------
<br>
### Exporting KML (Google Earth)
```{r}
writeOGR(locs.gb, dsn="locsgb.kml", layer="locs.gb", driver="KML")
```
### Reading KML
```{r}
newmap <- readOGR("locsgb.kml", layer="locs.gb")
```
### Save as shapefile
```{r}
writePointsShape(locs.gb, "locsgb")
```
### Reading shapefiles
```{r}
gb.shape <- readShapePoints("locsgb.shp")
plot(gb.shape)
```
Use `readShapePoly` to read polygon shapefiles, and `readShapeLines` to read polylines.
See also `shapefile` in `raster` package.
<br>
<br>
<br>
Changing projection of spatial vector data <a name="changeproj"></a>
-------------------------------------------
`spTransform` (package `sp`) will do the projection as long as the original and new projection are correctly specified.
<br>
### Projecting point dataset
To illustrate, let's project the dataframe with Laurus nobilis coordinates that we obtained above:
```{r}
summary(locs)
```
The original coordinates are in lat lon format. Let's define the new desired projection:
Lambert Azimuthal Equal Area in this case
(look up parameters at [http://spatialreference.org](http://spatialreference.org))
```{r}
crs.laea <- CRS("+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs") # Lambert Azimuthal Equal Area
locs.laea <- spTransform(locs, crs.laea) # spTransform makes the projection
```
<br>
### Projecting shapefile of countries
```{r}
plot(countriesLow) # countries map in geographical projection
country.laea <- spTransform(countriesLow, crs.laea) # project
```
Let's plot this:
```{r}
plot(locs.laea, pch=20, col="steelblue")
plot(country.laea, add=T)
# define spatial limits for plotting
plot(locs.laea, pch=20, col="steelblue", xlim=c(1800000, 3900000), ylim=c(1000000, 3000000))
plot(country.laea, add=T)
```
<br>
[Back to Contents](#contents)
<br>
<br>
<br>
<br>
<br>
<br>
4. USING RASTER (GRID) DATA <a name="raster"></a>
===========================
<br>
### Downloading raster climate data from internet <a name="getdata"></a>
The `getData` function from the `dismo` package will easily retrieve climate data, elevation, administrative boundaries, etc. Check also the excellent [rWBclimate package](http://ropensci.org/packages/rwbclimate.html) by rOpenSci with additional functionality.
```{r}
tmin <- getData("worldclim", var="tmin", res=10) # this will download
# global data on minimum temperature at 10' resolution
```
<br>
### Loading a raster layer <a name="loadraster"></a>
```{r}
tmin1 <- raster(paste(getwd(), "/wc10/tmin1.bil", sep="")) # Tmin for January
```
Easy! The `raster` function reads many different formats, including Arc ASCII grids or netcdf files (see raster help). And values are stored on disk instead of memory! (useful for large rasters)
```{r}
fromDisk(tmin1)
```
Let's examine the raster layer:
```{r}
tmin1 <- tmin1/10 # Worldclim temperature data come in decimal degrees
tmin1 # look at the info
plot(tmin1)
```
<br>
### Creating a raster stack <a name="rasterstack"></a>
A raster stack is collection of many raster layers with the same projection, spatial extent and resolution.
Let's collect several raster files from disk and read them as a single raster stack:
```{r message=FALSE, warning=FALSE}
library(gtools)
file.remove(paste(getwd(), "/wc10/", "tmin_10m_bil.zip", sep=""))
list.ras <- mixedsort(list.files(paste(getwd(), "/wc10/", sep=""), full.names=T, pattern=".bil"))
list.ras # I have just collected a list of the files containing monthly temperature values
tmin.all <- stack(list.ras)
tmin.all
tmin.all <- tmin.all/10
plot(tmin.all)
```
<br>
### Raster bricks <a name="rasterbrick"></a>
A rasterbrick is similar to a raster stack (i.e. multiple layers with the same extent and resolution), but all the data must be stored in a single file on disk.
```{r}
tmin.brick <- brick(tmin.all) # creates rasterbrick
```
<br>
### Crop rasters <a name="cropraster"></a>
Crop raster manually (drawing region of interest):
```{r eval=FALSE}
plot(tmin1)
newext <- drawExtent() # click twice on the map to select the region of interest
tmin1.c <- crop(tmin1, newext)
plot(tmin1.c)
```
Alternatively, provide coordinates for the limits of the region of interest:
```{r}
newext <- c(-10, 10, 30, 50)
tmin1.c <- crop(tmin1, newext)
plot(tmin1.c)
tmin.all.c <- crop(tmin.all, newext)
plot(tmin.all.c)
```
<br>
### Define spatial projection of the rasters <a name="projectionraster"></a>
```{r}
crs.geo # defined above
projection(tmin1.c) <- crs.geo
projection(tmin.all.c) <- crs.geo
tmin1.c # notice info at coord.ref.
```
<br>
### Changing projection <a name="changeprojraster"></a>
Use `projectRaster` function:
```{r}
tmin1.proj <- projectRaster(tmin1.c, crs="+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +units=m +no_defs") # can also use a template raster, see ?projectRaster
tmin1.proj # notice info at coord.ref.
plot(tmin1.proj)
```
<br>
### Plotting raster data <a name="plotraster"></a>
Different plotting functions:
```{r}
histogram(tmin1.c)
pairs(tmin.all.c)
persp(tmin1.c)
contour(tmin1.c)
contourplot(tmin1.c)
levelplot(tmin1.c)
#plot3D(tmin1.c)
bwplot(tmin.all.c)
densityplot(tmin1.c)
```
### Spatial autocorrelation <a name="autocorrelation"></a>
```{r}
Moran(tmin1.c) # global Moran's I
tmin1.Moran <- MoranLocal(tmin1.c)
plot(tmin1.Moran)
```
### Extract values from raster <a name="extract"></a>
Use `extract` function:
```{r}
head(locs) # we'll obtain tmin values for our points
projection(tmin1) <- crs.geo
locs$tmin1 <- extract(tmin1, locs) # raster values
# are incorporated to the dataframe
head(locs)
```
You can also extract values for a given region instead of the whole raster:
```{r eval=FALSE}
plot(tmin1.c)
reg.clim <- extract(tmin1.c, drawExtent()) # click twice to
# draw extent of the region of interest
summary(reg.clim)
```
Using `rasterToPoints`:
```{r}
# rasterToPoints
tminvals <- rasterToPoints(tmin1.c)
head(tminvals)
```
And also, the `click` function will get values from particular locations in the map
```{r eval=FALSE}
plot(tmin1.c)
click(tmin1.c, n=3) # click n times in the map to get values
```
<br>
### Rasterize points, lines or polygons <a name="rasterize"></a>
```{r}
locs2ras <- rasterize(locs.gb, tmin1, field=rep(1,nrow(locs.gb)))
locs2ras
plot(locs2ras, xlim=c(-10,10), ylim=c(45, 60), legend=F)
data(wrld_simpl)
plot(wrld_simpl, add=T)
```
<br>
### Changing raster resolution <a name="resolution"></a>
Use `aggregate` function:
```{r}
tmin1.lowres <- aggregate(tmin1.c, fact=2, fun=mean)
tmin1.lowres
tmin1.c # compare
par(mfcol=c(1,2))
plot(tmin1.c, main="original")
plot(tmin1.lowres, main="low resolution")
```
### Spline interpolation <a name="interpolation"></a>
```{r message=FALSE, warning=FALSE}
xy <- data.frame(xyFromCell(tmin1.lowres, 1:ncell(tmin1.lowres))) # get raster cell coordinates
head(xy)
vals <- getValues(tmin1.lowres)
library(fields)
spline <- Tps(xy, vals) # thin plate spline
intras <- interpolate(tmin1.c, spline)
intras # note new resolution
plot(intras)
intras <- mask(intras, tmin1.c) # mask to land areas only
plot(intras)
title("Interpolated raster")
```
### Setting all rasters to the same extent, projection and resolution all in one <a name="spatialsync"></a>
See `spatial_sync_raster` function from `spatial.tools` package.
<br>
### Elevations, slope, aspect, etc <a name="elevation"></a>
<br>
Download elevation data from internet:
```{r}
elevation <- getData('alt', country='ESP')
```
Some quick maps:
```{r}
x <- terrain(elevation, opt=c('slope', 'aspect'), unit='degrees')
plot(x)
slope <- terrain(elevation, opt='slope')
aspect <- terrain(elevation, opt='aspect')
hill <- hillShade(slope, aspect, 40, 270)
plot(hill, col=grey(0:100/100), legend=FALSE, main='Spain')
plot(elevation, col=rainbow(25, alpha=0.35), add=TRUE)
```
### Saving and exporting raster data <a name="saveraster"></a>
Saving raster to file:
```{r}
writeRaster(tmin1.c, filename="tmin1.c.grd")
writeRaster(tmin.all.c, filename="tmin.all.grd")
```
`writeRaster` can export to many different file types, see help.
<br>
Exporting to KML (Google Earth)
```{r}
tmin1.c <- raster(tmin.all.c, 1)
KML(tmin1.c, file="tmin1.kml")
KML(tmin.all.c) # can export multiple layers
```
<br>
[Back to Contents](#contents)
<br>
<br>
<br>
<br>
5. SPATIAL STATISTICS (just a glance) <a name="spatstats"></a>
=====================================
<br>
### Point pattern analysis <a name="pointpatterns"></a>
Some useful packages:
```{r message=FALSE}
library(spatial)
library(spatstat)
library(spatgraphs)
library(ecespa) # ecological focus
```
See [CRAN Spatial Task View](http://cran.r-project.org/web/views/Spatial.html).
Let's do a quick example with Ripley's K function:
```{r}
data(fig1)
plot(fig1) # point pattern
data(Helianthemum)
cosa12 <- K1K2(Helianthemum, j="deadpl", i="survpl", r=seq(0,200,le=201),
nsim=99, nrank=1, correction="isotropic")
plot(cosa12$k1k2, lty=c(2, 1, 2), col=c(2, 1, 2), xlim=c(0, 200),
main= "survival- death",ylab=expression(K[1]-K[2]), legend=FALSE)
```
<br>
### Geostatistics <a name="geostatistics"></a>
Some useful packages:
```{r message=FALSE, eval=FALSE}
library(gstat)
library(geoR)
library(akima) # for spline interpolation
library(spdep) # dealing with spatial dependence
```
See [CRAN Spatial Task View](http://cran.r-project.org/web/views/Spatial.html).
<br>
[Back to Contents](#contents)
<br>
<br>
<br>
<br>
6. INTERACTING WITH OTHER GIS <a name="othergis"></a>
===============================================
```{r message=F, eval=F}
library(spgrass6) # GRASS
library(RPyGeo) # ArcGis (Python)
library(RSAGA) # SAGA
library(spsextante) # Sextante
```
<br>
[Back to Contents](#contents)
<br>
<br>
<br>
<br>
7. OTHER USEFUL PACKAGES <a name="otherpackages"></a>
=========================
```{r message=FALSE, eval=FALSE}
library(Metadata) # automatically collates data from online GIS datasets (land cover, pop density, etc) for a given set of coordinates
#library(GeoXp) # Interactive exploratory spatial data analysis
example(columbus)
histomap(columbus,"CRIME")
library(maptools)
# readGPS
library(rangeMapper) # plotting species distributions, richness and traits
# Species Distribution Modelling
library(dismo)
library(biomod2)
library(SDMTools)