├── .gitattributes
├── figure
├── gmap11.png
├── gmap12.png
├── gmap21.png
├── gmap22.png
├── gmap31.png
├── gmap32.png
├── unnamed-chunk-10.png
├── unnamed-chunk-11.png
├── unnamed-chunk-12.png
├── unnamed-chunk-13.png
├── unnamed-chunk-14.png
├── unnamed-chunk-16.png
├── unnamed-chunk-18.png
├── unnamed-chunk-19.png
├── unnamed-chunk-21.png
├── unnamed-chunk-22.png
├── unnamed-chunk-23.png
├── unnamed-chunk-29.png
├── unnamed-chunk-32.png
├── unnamed-chunk-37.png
├── unnamed-chunk-38.png
├── unnamed-chunk-43.png
├── unnamed-chunk-45.png
├── unnamed-chunk-50.png
├── unnamed-chunk-51.png
├── unnamed-chunk-6.png
├── unnamed-chunk-201.png
├── unnamed-chunk-202.png
├── unnamed-chunk-331.png
├── unnamed-chunk-332.png
├── unnamed-chunk-411.png
├── unnamed-chunk-412.png
├── unnamed-chunk-441.png
├── unnamed-chunk-442.png
├── unnamed-chunk-443.png
├── unnamed-chunk-444.png
├── unnamed-chunk-445.png
├── unnamed-chunk-446.png
├── unnamed-chunk-447.png
├── unnamed-chunk-448.png
├── unnamed-chunk-521.png
├── unnamed-chunk-522.png
├── unnamed-chunk-541.png
├── unnamed-chunk-542.png
├── unnamed-chunk-581.png
└── unnamed-chunk-582.png
├── README.md
├── .gitignore
├── R-GIS_tutorial.Rmd
└── R-GIS_tutorial.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.html linguist-detectable=false
2 | *.Rmd linguist-language=R
3 |
--------------------------------------------------------------------------------
/figure/gmap11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/gmap11.png
--------------------------------------------------------------------------------
/figure/gmap12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/gmap12.png
--------------------------------------------------------------------------------
/figure/gmap21.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/gmap21.png
--------------------------------------------------------------------------------
/figure/gmap22.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/gmap22.png
--------------------------------------------------------------------------------
/figure/gmap31.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/gmap31.png
--------------------------------------------------------------------------------
/figure/gmap32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/gmap32.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-10.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-11.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-12.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-13.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-14.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-14.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-16.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-18.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-18.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-19.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-19.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-21.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-21.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-22.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-22.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-23.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-23.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-29.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-29.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-32.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-37.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-37.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-38.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-38.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-43.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-43.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-45.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-45.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-50.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-50.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-51.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-51.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-6.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-201.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-201.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-202.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-202.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-331.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-331.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-332.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-332.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-411.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-411.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-412.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-412.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-441.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-441.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-442.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-442.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-443.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-443.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-444.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-444.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-445.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-445.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-446.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-446.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-447.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-447.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-448.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-448.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-521.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-521.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-522.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-522.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-541.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-541.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-542.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-542.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-581.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-581.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-582.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Pakillo/R-GIS-tutorial/HEAD/figure/unnamed-chunk-582.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Spatial data in R: Using R as a GIS
3 | ========================================================
4 |
5 |
6 | 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.
7 |
8 |
9 | [Francisco Rodriguez-Sanchez](http://sites.google.com/site/rodriguezsanchezf)
10 |
11 |
12 | v 2.2
13 |
14 | 27-01-2015
15 |
16 | Licence: [CC BY 4.0](http://creativecommons.org/licenses/by/4.0/)
17 |
18 |
19 | Check out latest version at [http://pakillo.github.io/R-GIS-tutorial](http://pakillo.github.io/R-GIS-tutorial)
20 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .Rproj.user
2 | .Rhistory
3 | .RData
4 | 36.1.-5.65.png
5 | 36.1.-5.65.png.rda
6 | 53.086.-2.31.png
7 | 53.086.-2.31.png.rda
8 | ESP2_msk_alt.grd
9 | ESP2_msk_alt.gri
10 | ESP2_msk_alt.vrt
11 | ESP_msk_alt.grd
12 | ESP_msk_alt.gri
13 | ESP_msk_alt.vrt
14 | France.gfw
15 | France.gif
16 | France.prj
17 | G_2013-02-25_185157_55492.kmz
18 | R-GIS tutorial.Rproj
19 | R-GIS_tutorial.html
20 | README.html
21 | gmap.png
22 | gmap.png.rda
23 | locsgb.dbf
24 | locsgb.kml
25 | locsgb.shp
26 | locsgb.shx
27 | newmap.png
28 | newmap.png.rda
29 | newmap2.png
30 | newmap2.png.rda
31 | newmap3.png
32 | newmap3.png.rda
33 | tmin.all.grd
34 | tmin.all.gri
35 | tmin1.c.grd
36 | tmin1.c.gri
37 | tmin1.kmz
38 | wc10
39 | BES_MacroEcology_SpatialRFlyer.jpg
40 | G_2013-12-18_150958_77388.kmz
41 | G_2013-12-19_012141_82937.kmz
42 | G_2013-12-19_123019_21910.kmz
43 |
--------------------------------------------------------------------------------
/R-GIS_tutorial.Rmd:
--------------------------------------------------------------------------------
1 |
2 | Spatial data in R: Using R as a GIS
3 | ========================================================
4 |
5 |
6 | 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.
7 |
8 |
9 | [Francisco Rodriguez-Sanchez](http://sites.google.com/site/rodriguezsanchezf)
10 |
11 |
12 | v 2.2
13 |
14 | 27-01-2015
15 |
16 | Licence: [CC BY 4.0](http://creativecommons.org/licenses/by/4.0/)
17 |
18 |
19 | Check out code and latest version at [GitHub](https://github.com/Pakillo/R-GIS-tutorial/blob/master/R-GIS_tutorial.md)
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | CONTENTS
28 | =========
29 |
30 |
31 |
32 |
33 | [1. INTRODUCTION](#intro)
34 |
35 |
36 |
37 |
38 | [2. GENERIC MAPPING](#mapping)
39 |
40 |
41 | * [Retrieving base maps from Google with `gmap` function in package `dismo`](#gmap)
42 |
43 | * [`RgoogleMaps`: Map your data onto Google Map tiles](#rgooglemaps)
44 |
45 | * [`googleVis`: visualise data in a web browser using Google Visualisation API](#googlevis)
46 |
47 | * [`RWorldMap`: mapping global data](#rworldmap)
48 |
49 |
50 |
51 |
52 | [3. SPATIAL VECTOR DATA (points, lines, polygons)](#vector)
53 |
54 |
55 | * [Example dataset: retrieve point occurrence data from GBIF](#gbif)
56 |
57 | * [Making data 'spatial'](#spatial)
58 |
59 | * [Define spatial projection](#projection)
60 |
61 | * [Quickly plotting point data on a map](#plot)
62 |
63 | * [Subsetting and mapping again](#subset)
64 |
65 | * [Mapping vectorial data (points, polygons, polylines)](#mapvector)
66 |
67 | * [Drawing polygons and polylines (e.g. for digitising)](#digitise)
68 |
69 | * [Converting between formats, reading in, and saving spatial vector data](#iovec)
70 |
71 | * [Changing projection of spatial vector data](#changeproj)
72 |
73 |
74 |
75 |
76 | [4. USING RASTER (GRID) DATA](#raster)
77 |
78 |
79 | * [Downloading raster climate data from internet](#getdata)
80 |
81 | * [Loading a raster layer](#loadraster)
82 |
83 | * [Creating a raster stack](#rasterstack)
84 |
85 | * [Raster bricks](#rasterbrick)
86 |
87 | * [Crop rasters](#cropraster)
88 |
89 | * [Define spatial projection of the rasters](#projectionraster)
90 |
91 | * [Changing projection](#changeprojraster)
92 |
93 | * [Plotting raster data](#plotraster)
94 |
95 | * [Spatial autocorrelation](#autocorrelation)
96 |
97 | * [Extract values from raster](#extract)
98 |
99 | * [Rasterize vector data (points, lines or polygons)](#rasterize)
100 |
101 | * [Changing raster resolution](#resolution)
102 |
103 | * [Spline interpolation](#interpolation)
104 |
105 | * [Setting all rasters to the same extent, projection and resolution all in one](#spatialsync)
106 |
107 | * [Elevations, slope, aspect, etc](#elevation)
108 |
109 | * [Saving and exporting raster data](#saveraster)
110 |
111 |
112 |
113 |
114 |
115 |
116 | [5. SPATIAL STATISTICS](#spatstats)
117 |
118 |
119 | * [Point pattern analysis](#pointpatterns)
120 |
121 | * [Geostatistics](#geostatistics)
122 |
123 |
124 |
125 |
126 |
127 | [6. INTERACTING WITH OTHER GIS](#othergis)
128 |
129 |
130 |
131 | [7. OTHER USEFUL PACKAGES](#otherpackages)
132 |
133 |
134 |
135 | [8. TO LEARN MORE](#tolearnmore)
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 | 1. INTRODUCTION
148 | ===============
149 |
150 |
151 |
152 | 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.
153 |
154 |
155 |
156 | #### Basic packages
157 |
158 | ```{r message=FALSE}
159 |
160 | library(sp) # classes for spatial data
161 | library(raster) # grids, rasters
162 | library(rasterVis) # raster visualisation
163 | library(maptools)
164 | library(rgeos)
165 | # and their dependencies
166 | ```
167 |
168 | 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.
169 |
170 |
171 | [Back to Contents](#contents)
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 | 2. GENERIC MAPPING
180 | ==================
181 |
182 |
183 |
184 |
185 | Retrieving base maps from Google with `gmap` function in package `dismo`
186 | ------------------------------------------------------------------------
187 |
188 | Some examples:
189 |
190 | Getting maps for countries:
191 |
192 | ```{r gmap1, message=FALSE}
193 |
194 | library(dismo)
195 |
196 | mymap <- gmap("France") # choose whatever country
197 | plot(mymap)
198 | ```
199 |
200 | Choose map type:
201 | ```{r gmap2, message=FALSE}
202 | mymap <- gmap("France", type="satellite")
203 | plot(mymap)
204 | ```
205 |
206 | Choose zoom level:
207 | ```{r gmap3, message=FALSE}
208 | mymap <- gmap("France", type="satellite", exp=3)
209 | plot(mymap)
210 | ```
211 |
212 | Save the map as a file in your working directory for future use
213 | ```{r message=FALSE}
214 | mymap <- gmap("France", type="satellite", filename="France.gmap")
215 | ```
216 |
217 |
218 | Now get a map for a region drawn at hand
219 |
220 | ```{r eval=FALSE}
221 |
222 | mymap <- gmap("Europe")
223 | plot(mymap)
224 |
225 | select.area <- drawExtent()
226 | # now click 2 times on the map to select your region
227 | mymap <- gmap(select.area)
228 | plot(mymap)
229 | # See ?gmap for many other possibilities
230 | ```
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 | `RgoogleMaps`: Map your data onto Google Map tiles
245 | ------------------------------------------------
246 |
247 | ```{r message=FALSE, results='hide'}
248 | library(RgoogleMaps)
249 | ```
250 |
251 |
252 | Get base maps from Google (a file will be saved in your working directory)
253 | ```{r message=FALSE, results='hide'}
254 | newmap <- GetMap(center=c(36.7,-5.9), zoom =10, destfile = "newmap.png", maptype = "satellite")
255 |
256 | # Now using bounding box instead of center coordinates:
257 | newmap2 <- GetMap.bbox(lonR=c(-5, -6), latR=c(36, 37), destfile = "newmap2.png", maptype="terrain")
258 |
259 | # Try different maptypes
260 | newmap3 <- GetMap.bbox(lonR=c(-5, -6), latR=c(36, 37), destfile = "newmap3.png", maptype="satellite")
261 | ```
262 |
263 |
264 | Now plot data onto these maps, e.g. these 3 points
265 | ```{r}
266 | PlotOnStaticMap(lat = c(36.3, 35.8, 36.4), lon = c(-5.5, -5.6, -5.8), zoom= 10,
267 | cex=4, pch= 19, col="red", FUN = points, add=F)
268 |
269 | ```
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 | `googleVis`: visualise data in a web browser using Google Visualisation API
284 | ---------------------------------------------------------------------------
285 |
286 | ```{r message=FALSE}
287 | library(googleVis)
288 | ```
289 |
290 | Run `demo(googleVis)` to see all the possibilities
291 |
292 |
293 | ```{r setOptions, echo=FALSE}
294 | op <- options(gvis.plot.tag = "chart")
295 | # necessary so that googleVis works with knitr, see http://lamages.blogspot.co.uk/2012/10/googlevis-032-is-released-better.html
296 | ```
297 |
298 |
299 |
300 | ### Example: plot country-level data
301 | ```{r results='asis', tidy=FALSE, eval=TRUE}
302 | data(Exports) # a simple data frame
303 | Geo <- gvisGeoMap(Exports, locationvar="Country", numvar="Profit",
304 | options=list(height=400, dataMode='regions'))
305 | plot(Geo)
306 | ```
307 | Using `print(Geo)` we can get the HTML code to embed the map in a web page!
308 |
309 |
310 |
311 | ### Example: Plotting point data onto a google map (internet)
312 | ```{r results='asis', tidy=FALSE, eval=TRUE}
313 | data(Andrew)
314 | M1 <- gvisMap(Andrew, "LatLong", "Tip",
315 | options=list(showTip=TRUE, showLine=F, enableScrollWheel=TRUE,
316 | mapType='satellite', useMapTypeControl=TRUE, width=800,height=400))
317 | plot(M1)
318 | ```
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 | `RWorldMap`: mapping global data
331 | --------------------------------
332 |
333 | Some examples
334 |
335 | ```{r message=FALSE, warning=FALSE}
336 |
337 | library(rworldmap)
338 |
339 | newmap <- getMap(resolution="coarse") # different resolutions available
340 | plot(newmap)
341 | ```
342 |
343 | ```{r message=FALSE}
344 | mapCountryData()
345 | ```
346 | ```{r message=FALSE}
347 | mapCountryData(mapRegion="europe")
348 | ```
349 | ```{r message=FALSE}
350 | mapGriddedData()
351 | ```
352 | ```{r message=FALSE}
353 | mapGriddedData(mapRegion="europe")
354 |
355 | ```
356 |
357 |
358 |
359 |
360 |
361 | [Back to Contents](#contents)
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 | 3. SPATIAL VECTOR DATA (points, lines, polygons)
379 | ================================================
380 |
381 |
382 |
383 |
384 | ### Example dataset: retrieve point occurrence data from GBIF
385 |
386 | Let's create an example dataset: retrieve occurrence data
387 | for the laurel tree (Laurus nobilis) from the
388 | [Global Biodiversity Information Facility (GBIF)](http://gbif.org)
389 | ```{r message=FALSE}
390 | library(dismo) # check also the nice "rgbif" package!
391 | laurus <- gbif("Laurus", "nobilis")
392 | # get data frame with spatial coordinates (points)
393 | locs <- subset(laurus, select=c("country", "lat", "lon"))
394 | head(locs) # a simple data frame with coordinates
395 |
396 | # Discard data with errors in coordinates:
397 | locs <- subset(locs, locs$lat<90)
398 | ```
399 |
400 |
401 |
402 | ### Making data 'spatial'
403 |
404 | So we have got a simple dataframe containing spatial coordinates.
405 | Let's make these data explicitly *spatial*
406 | ```{r}
407 | coordinates(locs) <- c("lon", "lat") # set spatial coordinates
408 | plot(locs)
409 | ```
410 |
411 |
412 | ### Define spatial projection
413 |
414 | Important: define geographical projection.
415 | Consult the appropriate PROJ.4 description here:
416 | [http://www.spatialreference.org/](http://www.spatialreference.org/)
417 | ```{r}
418 | crs.geo <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") # geographical, datum WGS84
419 | proj4string(locs) <- crs.geo # define projection system of our data
420 | summary(locs)
421 | ```
422 |
423 |
424 |
425 | ### Quickly plotting point data on a map
426 | ```{r}
427 | plot(locs, pch=20, col="steelblue")
428 | library(rworldmap)
429 | # library rworldmap provides different types of global maps, e.g:
430 | data(coastsCoarse)
431 | data(countriesLow)
432 | plot(coastsCoarse, add=T)
433 | ```
434 |
435 |
436 | ### Subsetting and mapping again
437 | ```{r}
438 | table(locs$country) # see localities of Laurus nobilis by country
439 |
440 | locs.gb <- subset(locs, locs$country=="United Kingdom") # select only locs in UK
441 | plot(locs.gb, pch=20, cex=2, col="steelblue")
442 | title("Laurus nobilis occurrences in UK")
443 | plot(countriesLow, add=T)
444 | summary(locs.gb)
445 |
446 | ```
447 |
448 |
449 |
450 |
451 | Mapping vectorial data (points, polygons, polylines)
452 | ---------------------------------------------------------------------
453 |
454 |
455 |
456 | ### Mapping vectorial data using `gmap` from `dismo`
457 |
458 |
459 | ```{r}
460 | gbmap <- gmap(locs.gb, type="satellite")
461 | locs.gb.merc <- Mercator(locs.gb) # Google Maps are in Mercator projection.
462 | # This function projects the points to that projection to enable mapping
463 | plot(gbmap)
464 | points(locs.gb.merc, pch=20, col="red")
465 | ```
466 |
467 |
468 |
469 |
470 |
471 |
472 |
473 | ### Mapping vectorial data with `RgoogleMaps`
474 |
475 |
476 | ```{r message=FALSE}
477 |
478 | require(RgoogleMaps)
479 |
480 | locs.gb.coords <- as.data.frame(coordinates(locs.gb)) # retrieves coordinates
481 | # (1st column for longitude, 2nd column for latitude)
482 | PlotOnStaticMap(lat = locs.gb.coords$lat, lon = locs.gb.coords$lon,
483 | zoom= 5, cex=1.4, pch= 19, col="red", FUN = points, add=F)
484 | ```
485 |
486 | Download base map from Google Maps and plot onto it
487 | ```{r message=FALSE}
488 | map.lim <- qbbox (locs.gb.coords$lat, locs.gb.coords$lon, TYPE="all") # define region
489 | # of interest (bounding box)
490 | mymap <- GetMap.bbox(map.lim$lonR, map.lim$latR, destfile = "gmap.png", maptype="satellite")
491 | # see the file in the wd
492 | PlotOnStaticMap(mymap, lat = locs.gb.coords$lat, lon = locs.gb.coords$lon,
493 | zoom= NULL, cex=1.3, pch= 19, col="red", FUN = points, add=F)
494 | ```
495 |
496 |
497 |
498 |
499 | Using different background (base map)
500 | ```{r message=FALSE}
501 | mymap <- GetMap.bbox(map.lim$lonR, map.lim$latR, destfile = "gmap.png", maptype="hybrid")
502 | PlotOnStaticMap(mymap, lat = locs.gb.coords$lat, lon = locs.gb.coords$lon,
503 | zoom= NULL, cex=1.3, pch= 19, col="red", FUN = points, add=F)
504 |
505 | ```
506 |
507 |
508 |
509 |
510 |
511 |
512 |
513 |
514 |
515 |
516 |
517 | ### Map vectorial data with `googleVis` (internet)
518 |
519 |
520 | ```{r results='asis', tidy=FALSE, eval=TRUE}
521 | points.gb <- as.data.frame(locs.gb)
522 | points.gb$latlon <- paste(points.gb$lat, points.gb$lon, sep=":")
523 | map.gb <- gvisMap(points.gb, locationvar="latlon", tipvar="country",
524 | options = list(showTip=T, showLine=F, enableScrollWheel=TRUE,
525 | useMapTypeControl=T, width=1400,height=800))
526 | plot(map.gb)
527 | #print(map.gb) # get HTML suitable for a webpage
528 | ```
529 |
530 |
531 |
532 |
533 |
534 |
535 |
536 |
537 | ### Drawing polygons and polylines (e.g. for digitising)
538 |
539 |
540 | ```{r eval=FALSE}
541 | plot(gbmap)
542 | mypolygon <- drawPoly() # click on the map to draw a polygon and press ESC when finished
543 | summary(mypolygon) # now you have a spatial polygon! Easy, isn't it?
544 | ```
545 |
546 |
547 |
548 |
549 |
550 |
551 |
552 | Converting between formats, reading in, and saving spatial vector data
553 | -------------------------------------------------------------------
554 |
555 |
556 |
557 | ### Exporting KML (Google Earth)
558 | ```{r}
559 | writeOGR(locs.gb, dsn="locsgb.kml", layer="locs.gb", driver="KML")
560 | ```
561 |
562 | ### Reading KML
563 | ```{r}
564 | newmap <- readOGR("locsgb.kml", layer="locs.gb")
565 | ```
566 |
567 | ### Save as shapefile
568 | ```{r}
569 | writePointsShape(locs.gb, "locsgb")
570 | ```
571 |
572 | ### Reading shapefiles
573 | ```{r}
574 | gb.shape <- readShapePoints("locsgb.shp")
575 | plot(gb.shape)
576 | ```
577 | Use `readShapePoly` to read polygon shapefiles, and `readShapeLines` to read polylines.
578 | See also `shapefile` in `raster` package.
579 |
580 |
581 |
582 |
583 |
584 |
585 |
586 | Changing projection of spatial vector data
587 | -------------------------------------------
588 |
589 | `spTransform` (package `sp`) will do the projection as long as the original and new projection are correctly specified.
590 |
591 |
592 |
593 | ### Projecting point dataset
594 |
595 | To illustrate, let's project the dataframe with Laurus nobilis coordinates that we obtained above:
596 | ```{r}
597 | summary(locs)
598 | ```
599 | The original coordinates are in lat lon format. Let's define the new desired projection:
600 | Lambert Azimuthal Equal Area in this case
601 | (look up parameters at [http://spatialreference.org](http://spatialreference.org))
602 | ```{r}
603 | 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
604 | locs.laea <- spTransform(locs, crs.laea) # spTransform makes the projection
605 | ```
606 |
607 |
608 |
609 | ### Projecting shapefile of countries
610 | ```{r}
611 | plot(countriesLow) # countries map in geographical projection
612 | country.laea <- spTransform(countriesLow, crs.laea) # project
613 | ```
614 |
615 | Let's plot this:
616 | ```{r}
617 | plot(locs.laea, pch=20, col="steelblue")
618 | plot(country.laea, add=T)
619 |
620 | # define spatial limits for plotting
621 | plot(locs.laea, pch=20, col="steelblue", xlim=c(1800000, 3900000), ylim=c(1000000, 3000000))
622 | plot(country.laea, add=T)
623 | ```
624 |
625 |
626 |
627 |
628 |
629 | [Back to Contents](#contents)
630 |
631 |
632 |
633 |
634 |
635 |
636 |
637 |
638 |
639 |
640 |
641 |
642 |
643 | 4. USING RASTER (GRID) DATA
644 | ===========================
645 |
646 |
647 |
648 |
649 | ### Downloading raster climate data from internet
650 | 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.
651 |
652 | ```{r}
653 | tmin <- getData("worldclim", var="tmin", res=10) # this will download
654 | # global data on minimum temperature at 10' resolution
655 | ```
656 |
657 |
658 |
659 | ### Loading a raster layer
660 |
661 | ```{r}
662 | tmin1 <- raster(paste(getwd(), "/wc10/tmin1.bil", sep="")) # Tmin for January
663 | ```
664 | 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)
665 | ```{r}
666 | fromDisk(tmin1)
667 | ```
668 |
669 | Let's examine the raster layer:
670 | ```{r}
671 | tmin1 <- tmin1/10 # Worldclim temperature data come in decimal degrees
672 | tmin1 # look at the info
673 | plot(tmin1)
674 | ```
675 |
676 |
677 |
678 | ### Creating a raster stack
679 |
680 | A raster stack is collection of many raster layers with the same projection, spatial extent and resolution.
681 | Let's collect several raster files from disk and read them as a single raster stack:
682 |
683 | ```{r message=FALSE, warning=FALSE}
684 |
685 | library(gtools)
686 | file.remove(paste(getwd(), "/wc10/", "tmin_10m_bil.zip", sep=""))
687 | list.ras <- mixedsort(list.files(paste(getwd(), "/wc10/", sep=""), full.names=T, pattern=".bil"))
688 | list.ras # I have just collected a list of the files containing monthly temperature values
689 | tmin.all <- stack(list.ras)
690 | tmin.all
691 | tmin.all <- tmin.all/10
692 | plot(tmin.all)
693 | ```
694 |
695 |
696 |
697 |
698 | ### Raster bricks
699 |
700 | 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.
701 |
702 | ```{r}
703 | tmin.brick <- brick(tmin.all) # creates rasterbrick
704 | ```
705 |
706 |
707 |
708 | ### Crop rasters
709 |
710 | Crop raster manually (drawing region of interest):
711 |
712 | ```{r eval=FALSE}
713 | plot(tmin1)
714 | newext <- drawExtent() # click twice on the map to select the region of interest
715 | tmin1.c <- crop(tmin1, newext)
716 | plot(tmin1.c)
717 | ```
718 |
719 | Alternatively, provide coordinates for the limits of the region of interest:
720 | ```{r}
721 | newext <- c(-10, 10, 30, 50)
722 | tmin1.c <- crop(tmin1, newext)
723 | plot(tmin1.c)
724 |
725 | tmin.all.c <- crop(tmin.all, newext)
726 | plot(tmin.all.c)
727 | ```
728 |
729 |
730 |
731 | ### Define spatial projection of the rasters
732 |
733 | ```{r}
734 | crs.geo # defined above
735 | projection(tmin1.c) <- crs.geo
736 | projection(tmin.all.c) <- crs.geo
737 | tmin1.c # notice info at coord.ref.
738 | ```
739 |
740 |
741 |
742 | ### Changing projection
743 |
744 | Use `projectRaster` function:
745 | ```{r}
746 | 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
747 | tmin1.proj # notice info at coord.ref.
748 | plot(tmin1.proj)
749 | ```
750 |
751 |
752 |
753 |
754 | ### Plotting raster data
755 |
756 | Different plotting functions:
757 | ```{r}
758 | histogram(tmin1.c)
759 | pairs(tmin.all.c)
760 | persp(tmin1.c)
761 | contour(tmin1.c)
762 | contourplot(tmin1.c)
763 | levelplot(tmin1.c)
764 | #plot3D(tmin1.c)
765 | bwplot(tmin.all.c)
766 | densityplot(tmin1.c)
767 | ```
768 |
769 |
770 | ### Spatial autocorrelation
771 |
772 | ```{r}
773 | Moran(tmin1.c) # global Moran's I
774 | tmin1.Moran <- MoranLocal(tmin1.c)
775 | plot(tmin1.Moran)
776 | ```
777 |
778 |
779 | ### Extract values from raster
780 |
781 | Use `extract` function:
782 | ```{r}
783 | head(locs) # we'll obtain tmin values for our points
784 | projection(tmin1) <- crs.geo
785 | locs$tmin1 <- extract(tmin1, locs) # raster values
786 | # are incorporated to the dataframe
787 | head(locs)
788 | ```
789 |
790 | You can also extract values for a given region instead of the whole raster:
791 | ```{r eval=FALSE}
792 | plot(tmin1.c)
793 | reg.clim <- extract(tmin1.c, drawExtent()) # click twice to
794 | # draw extent of the region of interest
795 | summary(reg.clim)
796 | ```
797 |
798 | Using `rasterToPoints`:
799 | ```{r}
800 | # rasterToPoints
801 | tminvals <- rasterToPoints(tmin1.c)
802 | head(tminvals)
803 | ```
804 |
805 | And also, the `click` function will get values from particular locations in the map
806 | ```{r eval=FALSE}
807 | plot(tmin1.c)
808 | click(tmin1.c, n=3) # click n times in the map to get values
809 | ```
810 |
811 |
812 |
813 | ### Rasterize points, lines or polygons
814 |
815 | ```{r}
816 | locs2ras <- rasterize(locs.gb, tmin1, field=rep(1,nrow(locs.gb)))
817 | locs2ras
818 | plot(locs2ras, xlim=c(-10,10), ylim=c(45, 60), legend=F)
819 | data(wrld_simpl)
820 | plot(wrld_simpl, add=T)
821 | ```
822 |
823 |
824 |
825 |
826 | ### Changing raster resolution
827 |
828 | Use `aggregate` function:
829 | ```{r}
830 | tmin1.lowres <- aggregate(tmin1.c, fact=2, fun=mean)
831 | tmin1.lowres
832 | tmin1.c # compare
833 | par(mfcol=c(1,2))
834 | plot(tmin1.c, main="original")
835 | plot(tmin1.lowres, main="low resolution")
836 | ```
837 |
838 |
839 | ### Spline interpolation
840 |
841 | ```{r message=FALSE, warning=FALSE}
842 | xy <- data.frame(xyFromCell(tmin1.lowres, 1:ncell(tmin1.lowres))) # get raster cell coordinates
843 | head(xy)
844 | vals <- getValues(tmin1.lowres)
845 | library(fields)
846 | spline <- Tps(xy, vals) # thin plate spline
847 | intras <- interpolate(tmin1.c, spline)
848 | intras # note new resolution
849 | plot(intras)
850 | intras <- mask(intras, tmin1.c) # mask to land areas only
851 | plot(intras)
852 | title("Interpolated raster")
853 | ```
854 |
855 | ### Setting all rasters to the same extent, projection and resolution all in one
856 |
857 | See `spatial_sync_raster` function from `spatial.tools` package.
858 |
859 |
860 |
861 |
862 | ### Elevations, slope, aspect, etc
863 |
864 |
865 | Download elevation data from internet:
866 | ```{r}
867 | elevation <- getData('alt', country='ESP')
868 | ```
869 |
870 | Some quick maps:
871 | ```{r}
872 | x <- terrain(elevation, opt=c('slope', 'aspect'), unit='degrees')
873 | plot(x)
874 |
875 | slope <- terrain(elevation, opt='slope')
876 | aspect <- terrain(elevation, opt='aspect')
877 | hill <- hillShade(slope, aspect, 40, 270)
878 | plot(hill, col=grey(0:100/100), legend=FALSE, main='Spain')
879 | plot(elevation, col=rainbow(25, alpha=0.35), add=TRUE)
880 | ```
881 |
882 |
883 | ### Saving and exporting raster data
884 |
885 |
886 | Saving raster to file:
887 |
888 | ```{r}
889 | writeRaster(tmin1.c, filename="tmin1.c.grd")
890 | writeRaster(tmin.all.c, filename="tmin.all.grd")
891 | ```
892 | `writeRaster` can export to many different file types, see help.
893 |
894 |
895 |
896 | Exporting to KML (Google Earth)
897 | ```{r}
898 | tmin1.c <- raster(tmin.all.c, 1)
899 | KML(tmin1.c, file="tmin1.kml")
900 | KML(tmin.all.c) # can export multiple layers
901 |
902 | ```
903 |
904 |
905 | [Back to Contents](#contents)
906 |
907 |
908 |
909 |
910 |
911 | 5. SPATIAL STATISTICS (just a glance)
912 | =====================================
913 |
914 |
915 |
916 | ### Point pattern analysis
917 |
918 | Some useful packages:
919 |
920 | ```{r message=FALSE}
921 | library(spatial)
922 | library(spatstat)
923 | library(spatgraphs)
924 | library(ecespa) # ecological focus
925 | ```
926 | See [CRAN Spatial Task View](http://cran.r-project.org/web/views/Spatial.html).
927 |
928 | Let's do a quick example with Ripley's K function:
929 | ```{r}
930 | data(fig1)
931 | plot(fig1) # point pattern
932 | data(Helianthemum)
933 | cosa12 <- K1K2(Helianthemum, j="deadpl", i="survpl", r=seq(0,200,le=201),
934 | nsim=99, nrank=1, correction="isotropic")
935 | plot(cosa12$k1k2, lty=c(2, 1, 2), col=c(2, 1, 2), xlim=c(0, 200),
936 | main= "survival- death",ylab=expression(K[1]-K[2]), legend=FALSE)
937 |
938 | ```
939 |
940 |
941 |
942 | ### Geostatistics
943 |
944 | Some useful packages:
945 |
946 | ```{r message=FALSE, eval=FALSE}
947 | library(gstat)
948 | library(geoR)
949 | library(akima) # for spline interpolation
950 | library(spdep) # dealing with spatial dependence
951 | ```
952 | See [CRAN Spatial Task View](http://cran.r-project.org/web/views/Spatial.html).
953 |
954 |
955 |
956 | [Back to Contents](#contents)
957 |
958 |
959 |
960 |
961 |
962 | 6. INTERACTING WITH OTHER GIS
963 | ===============================================
964 |
965 | ```{r message=F, eval=F}
966 | library(spgrass6) # GRASS
967 | library(RPyGeo) # ArcGis (Python)
968 | library(RSAGA) # SAGA
969 | library(spsextante) # Sextante
970 |
971 | ```
972 |
973 |
974 | [Back to Contents](#contents)
975 |
976 |
977 |
978 |
979 |
980 |
981 | 7. OTHER USEFUL PACKAGES
982 | =========================
983 |
984 | ```{r message=FALSE, eval=FALSE}
985 | library(Metadata) # automatically collates data from online GIS datasets (land cover, pop density, etc) for a given set of coordinates
986 |
987 | #library(GeoXp) # Interactive exploratory spatial data analysis
988 | example(columbus)
989 | histomap(columbus,"CRIME")
990 |
991 | library(maptools)
992 | # readGPS
993 |
994 | library(rangeMapper) # plotting species distributions, richness and traits
995 |
996 |
997 | # Species Distribution Modelling
998 | library(dismo)
999 | library(biomod2)
1000 | library(SDMTools)
1001 |
1002 | library(BioCalc) # computes 19 bioclimatic variables from monthly climatic values (tmin, tmax, prec)
1003 |
1004 | ```
1005 |
1006 |
1007 | [Back to Contents](#contents)
1008 |
1009 |
1010 |
1011 |
1012 |
1013 | 8. TO LEARN MORE
1014 | ================
1015 |
1016 | * [ASDAR book](http://www.asdar-book.org/)
1017 |
1018 | * Packages help and vignettes, especially
1019 |
1020 | http://cran.r-project.org/web/packages/raster/vignettes/Raster.pdf
1021 | http://cran.r-project.org/web/packages/dismo/vignettes/sdm.pdf
1022 | http://cran.r-project.org/web/packages/sp/vignettes/sp.pdf
1023 |
1024 | * [CRAN Task View: Analysis of Spatial Data](http://cran.r-project.org/web/views/Spatial.html)
1025 |
1026 |
1027 | * [Introduction to Spatial Data and ggplot2](http://rpubs.com/RobinLovelace/intro-spatial)
1028 |
1029 | * [R spatial tips](http://spatial.ly/category/r-spatial-data-hints/)
1030 |
1031 | * [R wiki: tips for spatial data](http://rwiki.sciviews.org/doku.php?id=tips:spatial-data&s=spatial)
1032 |
1033 | * [Spatial analysis in R](http://www.maths.lancs.ac.uk/~rowlings/Teaching/Sheffield2013/index.html)
1034 |
1035 | * [Displaying time series, spatial and space-time data with R](http://oscarperpinan.github.io/spacetime-vis/)
1036 |
1037 | * [Notes on Spatial Data Operations in R](https://dl.dropboxusercontent.com/u/9577903/broomspatial.pdf)
1038 |
1039 | * [Analysing spatial point patterns in R](http://www.csiro.au/resources/pf16h)
1040 |
1041 | * [Spatial data in R](http://science.nature.nps.gov/im/datamgmt/statistics/r/advanced/Spatial.cfm)
1042 |
1043 | * [NCEAS Geospatial use cases](http://www.nceas.ucsb.edu/scicomp/usecases)
1044 |
1045 | * [Spatial Analyst](http://spatial-analyst.net)
1046 |
1047 | * [Making maps with R](http://www.molecularecologist.com/2012/09/making-maps-with-r/)
1048 |
1049 | * [The Visual Raster Cheat Sheet](http://www.rpubs.com/etiennebr/visualraster)
1050 |
1051 | * [R-SIG-Geo mailing list](https://stat.ethz.ch/mailman/listinfo/R-SIG-Geo)
1052 |
1053 | * [Geospatial data processing and analysis in R (slides)](http://rpubs.com/ajlyons/rspatialdata)
1054 |
1055 | * [rMaps](http://rmaps.github.io/)
1056 |
1057 |
1058 |
1059 |
1060 |
1061 |
1062 | [Back to Contents](#contents)
1063 |
1064 |
1065 |
1066 |
--------------------------------------------------------------------------------
/R-GIS_tutorial.md:
--------------------------------------------------------------------------------
1 |
2 | Spatial data in R: Using R as a GIS
3 | ========================================================
4 |
5 |
6 | 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.
7 |
8 |
9 | [Francisco Rodriguez-Sanchez](http://sites.google.com/site/rodriguezsanchezf)
10 |
11 |
12 | v 2.2
13 |
14 | 27-01-2015
15 |
16 | Licence: [CC BY 4.0](http://creativecommons.org/licenses/by/4.0/)
17 |
18 |
19 | Check out code and latest version at [GitHub](https://github.com/Pakillo/R-GIS-tutorial/blob/master/R-GIS_tutorial.md)
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | CONTENTS
28 | =========
29 |
30 |
31 |
32 |
33 | [1. INTRODUCTION](#intro)
34 |
35 |
36 |
37 |
38 | [2. GENERIC MAPPING](#mapping)
39 |
40 |
41 | * [Retrieving base maps from Google with `gmap` function in package `dismo`](#gmap)
42 |
43 | * [`RgoogleMaps`: Map your data onto Google Map tiles](#rgooglemaps)
44 |
45 | * [`googleVis`: visualise data in a web browser using Google Visualisation API](#googlevis)
46 |
47 | * [`RWorldMap`: mapping global data](#rworldmap)
48 |
49 |
50 |
51 |
52 | [3. SPATIAL VECTOR DATA (points, lines, polygons)](#vector)
53 |
54 |
55 | * [Example dataset: retrieve point occurrence data from GBIF](#gbif)
56 |
57 | * [Making data 'spatial'](#spatial)
58 |
59 | * [Define spatial projection](#projection)
60 |
61 | * [Quickly plotting point data on a map](#plot)
62 |
63 | * [Subsetting and mapping again](#subset)
64 |
65 | * [Mapping vectorial data (points, polygons, polylines)](#mapvector)
66 |
67 | * [Drawing polygons and polylines (e.g. for digitising)](#digitise)
68 |
69 | * [Converting between formats, reading in, and saving spatial vector data](#iovec)
70 |
71 | * [Changing projection of spatial vector data](#changeproj)
72 |
73 |
74 |
75 |
76 | [4. USING RASTER (GRID) DATA](#raster)
77 |
78 |
79 | * [Downloading raster climate data from internet](#getdata)
80 |
81 | * [Loading a raster layer](#loadraster)
82 |
83 | * [Creating a raster stack](#rasterstack)
84 |
85 | * [Raster bricks](#rasterbrick)
86 |
87 | * [Crop rasters](#cropraster)
88 |
89 | * [Define spatial projection of the rasters](#projectionraster)
90 |
91 | * [Changing projection](#changeprojraster)
92 |
93 | * [Plotting raster data](#plotraster)
94 |
95 | * [Spatial autocorrelation](#autocorrelation)
96 |
97 | * [Extract values from raster](#extract)
98 |
99 | * [Rasterize vector data (points, lines or polygons)](#rasterize)
100 |
101 | * [Changing raster resolution](#resolution)
102 |
103 | * [Spline interpolation](#interpolation)
104 |
105 | * [Setting all rasters to the same extent, projection and resolution all in one](#spatialsync)
106 |
107 | * [Elevations, slope, aspect, etc](#elevation)
108 |
109 | * [Saving and exporting raster data](#saveraster)
110 |
111 |
112 |
113 |
114 |
115 |
116 | [5. SPATIAL STATISTICS](#spatstats)
117 |
118 |
119 | * [Point pattern analysis](#pointpatterns)
120 |
121 | * [Geostatistics](#geostatistics)
122 |
123 |
124 |
125 |
126 |
127 | [6. INTERACTING WITH OTHER GIS](#othergis)
128 |
129 |
130 |
131 | [7. OTHER USEFUL PACKAGES](#otherpackages)
132 |
133 |
134 |
135 | [8. TO LEARN MORE](#tolearnmore)
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 | 1. INTRODUCTION
148 | ===============
149 |
150 |
151 |
152 | 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.
153 |
154 |
155 |
156 | #### Basic packages
157 |
158 |
159 | ```r
160 |
161 | library(sp) # classes for spatial data
162 | library(raster) # grids, rasters
163 | library(rasterVis) # raster visualisation
164 | library(maptools)
165 | library(rgeos)
166 | # and their dependencies
167 | ```
168 |
169 |
170 | 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.
171 |
172 |
173 | [Back to Contents](#contents)
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 | 2. GENERIC MAPPING
182 | ==================
183 |
184 |
185 |
186 |
187 | Retrieving base maps from Google with `gmap` function in package `dismo`
188 | ------------------------------------------------------------------------
189 |
190 | Some examples:
191 |
192 | Getting maps for countries:
193 |
194 |
195 | ```r
196 |
197 | library(dismo)
198 |
199 | mymap <- gmap("France") # choose whatever country
200 | plot(mymap)
201 | ```
202 |
203 |  
204 |
205 |
206 | Choose map type:
207 |
208 | ```r
209 | mymap <- gmap("France", type = "satellite")
210 | plot(mymap)
211 | ```
212 |
213 |  
214 |
215 |
216 | Choose zoom level:
217 |
218 | ```r
219 | mymap <- gmap("France", type = "satellite", exp = 3)
220 | plot(mymap)
221 | ```
222 |
223 |  
224 |
225 |
226 | Save the map as a file in your working directory for future use
227 |
228 | ```r
229 | mymap <- gmap("France", type = "satellite", filename = "France.gmap")
230 | ```
231 |
232 |
233 |
234 | Now get a map for a region drawn at hand
235 |
236 |
237 | ```r
238 |
239 | mymap <- gmap("Europe")
240 | plot(mymap)
241 |
242 | select.area <- drawExtent()
243 | # now click 2 times on the map to select your region
244 | mymap <- gmap(select.area)
245 | plot(mymap)
246 | # See ?gmap for many other possibilities
247 | ```
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 | `RgoogleMaps`: Map your data onto Google Map tiles
263 | ------------------------------------------------
264 |
265 |
266 | ```r
267 | library(RgoogleMaps)
268 | ```
269 |
270 |
271 |
272 | Get base maps from Google (a file will be saved in your working directory)
273 |
274 | ```r
275 | newmap <- GetMap(center = c(36.7, -5.9), zoom = 10, destfile = "newmap.png",
276 | maptype = "satellite")
277 |
278 | # Now using bounding box instead of center coordinates:
279 | newmap2 <- GetMap.bbox(lonR = c(-5, -6), latR = c(36, 37), destfile = "newmap2.png",
280 | maptype = "terrain")
281 |
282 | # Try different maptypes
283 | newmap3 <- GetMap.bbox(lonR = c(-5, -6), latR = c(36, 37), destfile = "newmap3.png",
284 | maptype = "satellite")
285 | ```
286 |
287 |
288 |
289 | Now plot data onto these maps, e.g. these 3 points
290 |
291 | ```r
292 | PlotOnStaticMap(lat = c(36.3, 35.8, 36.4), lon = c(-5.5, -5.6, -5.8), zoom = 10,
293 | cex = 4, pch = 19, col = "red", FUN = points, add = F)
294 | ```
295 |
296 | 
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 | `googleVis`: visualise data in a web browser using Google Visualisation API
312 | ---------------------------------------------------------------------------
313 |
314 |
315 | ```r
316 | library(googleVis)
317 | ```
318 |
319 |
320 | Run `demo(googleVis)` to see all the possibilities
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 | ### Example: plot country-level data
329 |
330 | ```r
331 | data(Exports) # a simple data frame
332 | Geo <- gvisGeoMap(Exports, locationvar="Country", numvar="Profit",
333 | options=list(height=400, dataMode='regions'))
334 | plot(Geo)
335 | ```
336 |
337 |
338 |
339 |
340 |
341 |
342 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |