forked from taniaguerrero/CASA0005repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-prac1.Rmd
817 lines (504 loc) · 47.3 KB
/
01-prac1.Rmd
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
# (PART) GIS tools {-}
# Geographic Information
## Learning outcomes
By the end of this practical you should be able to:
1. Describe and explain GIS data formats and databases
2. Source and pre-process spatial data
3. Load and undertaken some basic manipulation of spatial data in: ArcMap, QGIS and R
4. Evaluate the (dis)advantages of each GIS you have used
## Homework
Outside of our schedulded sessions you should be doing around 12 hours of extra study per week. Feel free to follow your own GIS interests, but good places to start include the following:
::: {.infobox .assignment data-latex="{note}"}
**Assignment**
This week you should undertake wider data exploration and reading to find a topic you might be interested in progressing with. I'd recommend starting with a data search first to avoid proposing a research area then forcing potentially unsuitable data to fit it.
:::
::: {.infobox .note data-latex="{note}"}
**Reading**
Each week i'll provide a core chapter to support the skills taught here. However, **you are free to read whatever interests you** and Adam and I strongly encourage this, so please don't be constrained to this recommendation. Consult the [reading list](https://rl.talis.com/3/ucl/lists/139FBAF8-DACD-60FB-8BDC-E9C9E09BA885.html?lang=en-GB&login=1), practical and lecture each week for more ideas.
This week:
* [Chapter 2 "Geographic data in R"](https://geocompr.robinlovelace.net/spatial-class.html) from Geocomputation with R by Lovelace, Nowosad and Muenchow (2020).
:::
## Recommended listening
Some of these practicals are long, take regular breaks and have a listen to some of our fav tunes each week.
[Andy](https://www.youtube.com/watch?v=1egwdCGi_dA&list=OLAK5uy_lGype0gR4vyIE0J2hvNYtpifSbNynJTNk&index=1)
[Adam](https://open.spotify.com/album/0XXI8pxXeS9cvpBX9bB3hh)... This week, wrap your ears around this piece of liquid gold from Japan’s finest, Makoto.
## The Basics of Geographic Information
Geographic data, geospatial data or geographic information is data that identifies the location of features on Earth. There are two main types of data which are used in GIS applications to represent the real world. **Vectors** that are composed of points, lines and polygons and **rasters** that are grids of cells with individual values...
```{r echo=FALSE, out.width = "300pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/rasvec.jpg')
```
In the above example the features in the real world (e.g. lake, forest, marsh and grassland) have been represented by points, lines and polygons (vector) or discrete grid cells (raster) of a certain size (e.g. 1 x 1m) specifying land cover type.
### Data types in statistics
Before we go any further let's just quick go over the different types of data you might encounter
Continuous data can be measured on some sort of scale and can have any value on it such as height and weight.
Discrete data have finite values. It can be numeric such as number of shoes or categorial such as positive or negative.
Foot length would be continuous data but shoe size would be discrete data.
```{r echo=FALSE, out.width = "450", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/continuous_discrete.png')
```
Nominal data has labels without any quantitative value such as hair colour or type of animal.
Oridnal data has an order or scale, for example if you have ever seen the chilli rating system on food labels or filled a happiness survey with a range between 1 and 10 --- that's ordinal. Here the order matters, but not the difference between them.
Binary data is that that can have only two possible outcomes, yes and no or shark and not shark.
```{r echo=FALSE, out.width = "550pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/nominal_ordinal_binary.png')
```
### Important GIS data formats
There are a number of commonly used geographic data formats that store vector and raster data that you will come across during this course and it’s important to understand what they are, how they represent data and how you can use them.
#### Shapefiles
Perhaps the most commonly used GIS data format is the shapefile. Shapefiles were developed by [ESRI](http://www.esri.com/), one of the first and now certainly the largest commercial GIS company in the world. Despite being developed by a commercial company, they are mostly an open format and can be used (read and written) by a host of GIS Software applications.
A shapefile is actually a collection of files –-- at least three of which are needed for the shapefile to be displayed by GIS software. They are:
1. ```.shp``` - the file which contains the feature geometry
2. ```.shx``` - an index file which stores the position of the feature IDs in the ```.shp ``` file
3. ```.dbf``` - the file that stores all of the attribute information associated with the coordinates – this might be the name of the shape or some other information associated with the feature
4. ```.prj``` - the file which contains all of the coordinate system information (the location of the shape on Earth's surface). Data can be displayed without a projection, but the ```.prj``` file allows software to display the data correctly where data with different projections might be being used
On Twitter and want to see the love for shapefiles....have a look at [the shapefile account](https://twitter.com/shapefiIe)
#### GeoJSON
GeoJSON [Geospatial Data Interchange format for JavaScript Object Notation](http://geojson.org/) is becoming an increasingly popular spatial data format, particularly for web-based mapping as it is based on JavaScript Object Notation. Unlike a shapefile in a GeoJSON, the attributes, boundaries and projection information are all contained in the same file.
#### Shapefile and GeoJSON
We're now going to explore a shapefile (```.shp``` ) and GeoJSON (```.geojson```) in action.
Go to: http://geojson.io/#map=16/51.5247/-0.1339
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/JSONwebsite.png')
```
1. Using the drawing tools to the right of the map window, create 3 objects: a point, line and a polygon as I have done above. Click on your polygon and colour it red and colour your point green
2. Using the ‘Save’ option at the top of the map, save two copies of your new data – one in ```.geojson``` format and one in ```.shp``` format
3. Open your two newly saved files in a text editor such as notepad or notepad++. For the shapefile you might have to unzip the folder then open each file individually. What do you notice about the similarities or differences between the two ways that the data are encoded?
#### Raster data
Most raster data is now provided in GeoTIFF (```.tiff```) format, which stands for Geostarionary Earth Orbit Tagged Image File. The GeoTIFF data format was created by NASA and is a standard public domain format. All necesary information to establish the location of the data on Earth's surface is embedded into the image. This includes: map projection, coordinate system, ellipsoid and datum type.
#### Other data formats
Aforementioned data types and formats are likely to be the ones you predominately encounter. However there are several more used within spatial analysis. These include:
**Vector**
* GML (Geography Markup Language –-- gave birth to Keyhold Markup Language (KML))
**Raster**
* Band SeQuential (BSQ) - technically a method for encoding data but commonly referred to as BSQ.
* Hierarchical Data Format (HDF)
* Arc Grid
There are normally valid reasons for storing data in one of these other formats. For example, BSQ are raster data with a separate text header file (```.hdr```) providing geographic spatial reference information. Earth observation data often monitors the electromagnetic spectrum in bands. Humans see in the visible range of the spectrum and our vision is composed of red, green and blue wavelengths. If we wanted to analyse just the red wavelength the BSQ format would let us *read in* only that data. In comparison a GeoTIFF might come with all the data 'packaged' in one file and when doing analysis over thousands of images would significantly slow things down. That said you can now often find GeoTIFFs separated in a similar format to BSQ and it's fairly straightforward to convert between raster formats.
#### Geodatabase
A geodatabase is a collection of geographic data held within a database. Geodatabases were developed by ESRI to overcome some of the limitations of shapefiles. They come in two main types: Personal (up to 1 TB) and File (limited to 250 - 500 MB), with Personal Geodatabases storing everything in a Microsoft Access database (```.mdb```) file and File Geodatabases offering more flexibility, storing everything as a series of folders in a file system. In the example below we can see that the FCC_Geodatabase (left hand pane) holds multiple points, lines, polygons, tables and raster layers in the contents tab.
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/geodatabase.png')
```
#### GeoPackage
```{r echo=FALSE, out.width = "100pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/geopkg.png')
```
A GeoPackage is an open, standards-based, platform-independent, portable, self-describing, compact format for transferring geospatial data. It stores spatial data layers (vector and raster) as a single file, and is based upon an SQLite database, a widely used relational database management system, permitting code based, reproducible and transparent workflows. As it stores data in a single file it is very easy to share, copy or move.
#### SpatiaLite
```{r echo=FALSE, out.width = "100pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/spatialite.png')
```
SpatialLite is an open-source library that extends SQLite core. Support is fairly limited and most software that supports SpatiaLite also supports GeoPackage, as they both build upon SQLite. It doesn't have any clear advantage over GeoPackage, however it is unable to support raster data.
#### PostGIS
```{r echo=FALSE, out.width = "100pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/postGIS.jpg')
```
PostGIS is an opensource database extender for PostrgeSQL. Essentially PostgreSQL is a database and PostGIS is an add on which permits spatial functions. The advantages of using PostGIS over a GeoPackage are that it allows users to access the data at the same time, can handle large data more efficiently and reduces processing time. In [this example](https://medium.com/@GispoLearning/learn-spatial-sql-and-master-geopackage-with-qgis-3-16b1e17f0291) calculating the number of bars per neighbourhood in Leon, Mexico the processing time reduced from 1.443 seconds (SQLite) to 0.08 seconds in PostGIS. However, data stored in PostGIS is much harder to share, move or copy.
#### What will I use
The variety of data formats can see a bit overwhelming. I still have to check how to load some of these data formats that I don't use frequently. But don't worry, most of the time you'll be using shapefiles, GeoPackages or raster data.
## General data flow
As Grolemund and Wickham state in [R for Data Science](https://r4ds.had.co.nz/)...
>"Data science is a huge field, and there’s no way you can master it by reading a single book."
However, a nice place to start is looking at the typical workflow of a data science (or GIS) project which you will see throuhgout these practicals, which is summarised nicely in this diagram produced by [Dr. Julia Lowndes](https://twitter.com/juliesquid) adpted from Grolemund and Wickham.
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/environmental_data_science_r4ds_general.png')
```
To being you have to **import** your data (not necessarily environmental) into R or someother kind of GIS to acatually be able to do any kind of analysis on it.
Once imported you might need to **tidy** the data. This really depends on what kind of data it is and we cover this later on in the course. However, putting all of your data into a consistent structure will be very beneficial when you have to do analysis on it --- as you can treat it all in the same way. Grolemund and Wickham state that data is tidy when "each column is a variable, and each row is an observation", we cover this more in next week in the [Tidying data] section.
When you have (or haven't) tidied data you then will most likely want to **transform** it. Grolemund and Wickham define this as "narrowing in on observations of interest (like all people in one city, or all data from the last year), creating new variables that are functions of existing variables (like computing speed from distance and time), and calculating a set of summary statistics (like counts or means)". However, from a GIS point of view I would also include putting all of your data into a similar projection, covered next week in [Changing projections] and any other basic process you might do before the core analysis. Arguably these processes could include things such as: clipping (cookie cutting your study area), buffering (making areas within a distance of a point) and intersecting (where two datasets overlap).
Tidying and transfrom = data wrangling. Remember from the introduction this could be 50-80% of a data science job!
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/dplyr_wrangling.png')
```
After you have transformed the data the next best thing to do is **visualise** it --- even with some basic summary statistics. This simple step will often let you look at your data in a different way and select more appropraite analysis.
Next up is **modelling**. Personally within GIS i'd say a better term is processing as the very data itself is usually a computer model of reality. The modelling or processing section is where you conduct the core analysis (more than the basic analysis already mentioned) and try to provide an answer to your research question.
Fianlly you have to **communicate** your study and outputs, it doesn't matter how good your data wrangling, modelling or processing is, if your intended audience can't interpret it, well, it's pretty much useless.
::: {.infobox .tip data-latex="{note}"}
In a few weeks come back and revisit this data flow section to see how what you have learnt fits the framework presented.
:::
## Data
The volume of geographic information which is freely available for use in the UK is increasing exponentially and spatially referenced data can often be found in many different places. In this practical we're going to use data from the London data store --- a free and open data-sharing portal provided by the Greater London Authority (GLA), also known as City Hall that is the devolved regional governance body of London.
We are going to get spatial data of the London boroughs and join flytipping (the illegal deposit of waste, commonly on road verges) data that is provided as a ```.csv``` file. ```.csv``` stands for comma-separated values (CSV) --- it uses a comma to separate each value.
At the end of this document I'll also run through some common sources of data that will stand you in good stead (be advantageous) for the rest of the course.
### File paths
In your N drive: create a new folder called GIS and within this a sub folder called wk1. It is up to you how you organise your files. Make sure you change the file paths where appropriate to your own.
### Data download
Firstly we need to get a spatial outline of the London boroughs. The geographic boundaries that are used in the UK are a complex, often inter-related, but ever changing mass of areas. For anyone new to the UK (or indeed not a trained quantitative geographer), it can be quite a daunting task to attempt to understand all of the boundaries that are in use. Fortunately the Office for National Statistics (ONS) has an online beginners guide to UK geography. If you need more information on the vast array of different UK geographies, go and explore these resources:
* http://geoportal.statistics.gov.uk/datasets/a-beginners-guide-to-uk-geography-2018-v1-0
* https://data.gov.uk/dataset/d7dd9437-20d0-448f-a61b-6e0939dcc642/hierarchical-representation-of-uk-statistical-geographies-december-2017
Let's download some data..
* Spatial Data
1. To get the data go to: https://data.london.gov.uk/
2. Search for Statistical GIS Boundary Files for London
3. Download the statistical-gis-boundaries-london.zip
4. Unzip the data and save it to your wk1 folder.
* CSV data
1. On the same website search for fly-tipping incidents
2. Download the ```.csv``` file
### Data pre-processing
**Question** Open the ```.csv``` in Excel, what do you notice about how the data is stored?
**Answer** The year is a column and for each area the values are repeated for different years. In our analysis it is easier to have the different years as a column and populated for each area. So, we want to go from this...
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/csv_original.png')
```
To this...
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/csv_pivot.png')
```
As we are going to use this dataset in ArcMap, QGIS and R I've done it in Excel using a pivot table. In future we'll use R to automate tasks like this.
1. Go to Insert > PivotTable
2. Select the original table and create a PivotTable in a new worksheet
3. The PivotTable Field box will appear, experiment with the different fields in each of the areas
I've used the following:
```{r echo=FALSE, out.width = "200pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/pivot_example.png')
```
Note how I've altered the total_action_taken to the sum of... as the original was displaying incorrectly, to do so:
1. Click on drop down button for total_action_taken > Value Field Settings > select Sum
It's important to think about what data we actually need in the next step and it's good practice to avoid data redundancy where possible.
**Spoiler** The spatial data we have downloaded already contains borough name, so we don't need it twice. However, we do need a field to link the two datasets on. You could use borough name, but when using text fields sometimes input variations can affect joins. For example, if you had the University of Manchester in one dataset and Manchester University in another the join would fail. Consequently it's usually best to join datasets on a code field.
Now save the Excel sheet that contains the pivot table as a new ```.csv```. Make sure that the first row of data holds the column titles. Remove all empty rows.
When saving the file also avoid any special characters (e.g. -) and spaces, use an underscore instead of spaces.
**Warning** Spatial software (especially ArcGIS) does not like file names with spaces or special characters.
### Data loading
Now it's time to load, inspect and do some basic manipulation of this data. As mentioned in the lecture there are several GIS software 'types', here we will repeat the same process across ArcGIS, QGIS and R. Each system has specific benefits, but in general there has been a recent shift towards the use of QGIS and R, both being opensource. ArcGIS was the first major spatial analysis software produced by the Environmental Systems Research Institute, Inc. (Esri), founded in 1969 by Jack Dangermond. Due to its high cost and lack of customisation it is now less commonly used within the research community.
```{r echo=FALSE, out.width = "300pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/ArcGISvsQGIS.png')
```
#### ArcGIS
ArcGIS is a huge and complex suite of software, see [ArcGIS suite] for more information. Thankfully it has an excellent help system –-- depending on the version you are using (they are all quite similar anyway) you can access the online help system here:
* http://resources.arcgis.com/en/help/main/10.2/
* http://resources.arcgis.com/en/help/main/10.1/
Here will we just be using:
* **ArcCatalog --- Similar to Windows Explorer, ArcCatalog allows you to manage your GIS files, folders and geodatabases**
* **ArcMap --- This is the programme you will use most often –-- it is the main mapping and spatial analysis element of ArcGIS**
#### ArcCatalog
* Find and run the ArcCatalog piece of software
* Once ArcCatalog Opens, go to File > Connect To Folder… and navigate to the N:\GIS folder, right click in the contents area and create a new File Geodatabase - i've called mine prac1.
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/file_geo.png')
```
You can import data layers into a Geodatabase within ArcCatalog, however we will do this in ArcMap.
Close ArcCatalog and **never** have both ArcCatalog and another ArcGIS product open at the same time.
#### ArcMap
##### Introduction
ArcMap is the core of the ArcGIS suite and where you would normally produce maps, carry out spatial analysis functions and automate processes.
1. Search for and open ArcMap
2. Upon opening select the database you just created in the default geodatabased fpor this map dialogue box
3. Click ok
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/default_database.png')
```
When the map document opens you should see something similar to the image below, highlighting some of the key buttons (without the data):
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/arcmap.png')
```
4. It's important to now set the map document up properly. Go File > Map Document Properties, enter the details you wish. You can see the connection to the Geodatabase we just made. Click store relative pathnames, this means as long as the data stays in the same position relative to the path then ArcMap can load all the layers. For example if you moved your work from the C: drive to an external drive, H:.
##### Load data
5. Using the **Plus** icon (add data layer) navigate to the extracted folder you saved earlier.
6. Open `London_Borough_Excluding_MHW.shp`, but feel free to explore the other data layers. In the left hand Table Of Contents you can unselect layers to turn them off or drag layers above or below to change the display order. In the example below the wards layer is showing above the borough layer.
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/display_order.png')
```
> **Note**, while we have loaded the shapefile, it is not stored in our Geodatabase yet.
**Useful tips**
* To the right of the document you will see the Catalog and Search tabs.The Catalog tab is a more compact version of ArcCatalog and will let you see what data is stored in the current Geodatabase --- you can use this at the same time as ArcMap. The search tab will let you find any analysis tool within ArcGIS. Try searching for Clip.
* If you right click on the boroughs layer (in the Table of Contents, left hand pane) you will see various options. Zoom to layer is very useful if you ever get lost in your ArcMap document.
7. Now right click on the borough layer (in the Table of Contents) and open the attribute table. You'll see the GSS_CODE field, which is the same code we output in our ```.csv```. If you now right click on a field you'll also be able to see the data type (e.g. string, integer). For example:
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/London_attribute_table.png')
```
##### Join data
We're now going to join our flytipping data to the London borough shapefile. So:
8. Right click on the london borough layer > Joins and Relates > Join
9. Select the GSS_CODE as the field in the layer to base the join on
10. Navigate to the ```.csv``` we created earlier
11. Select the code field that matches (in my case this is called Row Labels)
12. Select only to join matching records
13. Validate join and click OK
**You will get errors**, ArcMap does not like fields starting with numbers (e.g. 2012), dashes (e.g. -) or spaces. Feel free to change them in the original ```.csv``` but for this practical it is fine to continue.
14. The join should work, so reopen the attribute table for the layer London boroughs
> **Note**, the join we have made is not permanent. To do so we need to export the layer.
##### Export data
15. Right click on the london boroughs layer > Data > Export Data
16. The location should default to our GeoDatabase. Be sure to change the filename --- again avoid all of the characters (e.g. spaces and -) previously mentioned. Add the new data layer to the map and remove the old one (Right Click (on the layer) > Remove)
Now lets use the data we've joined to create a basic thematic map.
17. Right click on the new London borough layer > Properties
18. Under the Symbology tab select Graduated colors
19. Select the Value as one of the years of data we joined and change the classificaiton to something of your choice
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/symbology.png')
```
You should have something that looks like this:
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/thematicmap.png')
```
**We haven't talked about the Coordiante Reference System (CRS) (or Spatial Reference System (SRS)) of our map document**
A coordinate reference system is a series of parameters that define the coordinate system. Within GIS we use geographic or projected coordinate systems. The former uses a three-dimensional spherical surface to define locations of Earth, whereas the latter is defined on a flat, two-dimensional surface giving it constant lengths, angles and areas. We cover this in more detail later on.
In ArcMap we can specify what CRS we want to use by:
20. Right clicking on the map document > Data Frame Properties
You'll see that it is already set to Projected Coordinate Systems, National Grids, Europe, British National Grid. This is because ArcMap will default to the coordinate system of the first data layer loaded.
```{r echo=FALSE, out.width = "300pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/coorindate_system.png')
```
Save and then close your ArcMap document. We're now going to replicate this task in QGIS.
> **Note** As we are going to open the same files in difference GIS systems it is important to close the software before moving on. If you don't then files can be *locked* and unreadable as they are still considered to be in use.
### QGIS
#### Introduction
QGIS is very similar to ArcMap except that as it is open-source and free there are many add on packages that (or plugins) that provide additional functionality to the software.
#### Load data
1. Search for and open QGIS
2. Click on the open data source manager. Just above the word **browser** in the top left of the screen
```{r echo=FALSE, out.width = "700pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/qgis_datamanager.png')
```
3. Navigate to the London boroughs layer ```.shp``` and add it, you then have to close the data source manager
Just like in ArcMap you can right click on the layer to view the attribute table. Unlike ArcMap you have to load the ```.csv``` file into QGIS in order to join it to a shapefile.
4. Open the data source manager and select Delimited Text
5. Navigate to our ```.csv``` file and provide a suitable layer name
6. Under Record and Fields Options make sure the number of header lines to discard is 0 and the First record has field names box is selected (this is assuming you left a title for each column in your ```.csv```)
7. Under Geometry Definition select No geometry (attribute table only)
```{r echo=FALSE, out.width = "700pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/csv_datamanager.png')
```
Does the sample data seem right?
8. If so, click add then close
#### Join data
9. Right click on the London boroughs layer > Properties > Joins
10. Click the plus button at the bottom of the box
11. Complete the dialogue box
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/qgis_join.png')
```
#### Export data
Now instead of using a GeoDatabase, let's export to a GeoPackage.
12. Right click on the London boroughs layer > Export > Save Feature As
13. Select the GeoPackage format and complete the File name (the saved file name for the GeoPackage) and the Layer name (the name for this layer within the GeoPackage). Recall that a GeoPackage can store many data layers as a single file
14. The new layer will be added to the map, so you can remove the old one (Right click on the layer > Remove Layer). Make sure you remove the right one!
```{r echo=FALSE, out.width = "500pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/make_geopkg.png')
```
We've now made a GeoPackage that we can connect our map project to.
15. Under **Browser**, Right click on GeoPackage > New Connection > Navigate to your GeoPackage
16. Click the down arrow left to GeoPackage and you should see the one you just navigated to. Click the down arrow on the database and you can see your layer.
17. Now we are going to import our ```.csv ``` into our GeoPackage. To do so go: Database > DB Manager
18. Select your GeoPackage in the left hand pane
19. Import layer/file then select the ```.csv ```. Click Ok.
Again, remember that the ```.csv ``` in the Layers tab (bottom left) is the original. Remove it, then from the GeoPackage just click, hold and drag the ```.csv ``` into the layer pane.
Now let's make a quick thematic map like we did in ArcMap.
20. Right click on your London boroughs layer > Properties > Symbology
21. Select categorised and choose a data column and color ramp > click Classify
You could also select graduated, however our joined data fields are in the wrong data type. If you wish to change them follow [this guide](https://wiki.tuflow.com/index.php?title=QGIS_Change_Attribute_Type)
22. Save your QGIS project
You should have produced something like this:
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/QGIS_final.png')
```
**Spatial reference**
QGIS is similar but different to ArcMap. QGIS defaults to the Coordinate Reference System (CRS) WGS 84, or known by its European Petroleum Survey Group (EPSG) code 4326. However, when you add your first layer in will default to that CRS. We'll go into the background of EPSG next time.
You can change the CRS by going File > Properties and selecting CRS in the left hand pane.
### R
#### Introduction
R is both a programming language and software environment, originally designed for statistical computing and graphics. R’s great strength is that it is open-source, can be used on any computer operating system and free for anyone to use and contribute to. Because of this, it is rapidly becoming the statistical language of choice for many academics and has a huge user community with people constantly contributing new packages to carry out all manner of statistical, graphical and importantly for us, geographical tasks.
The purpose of this practical is just to demonstrate data loading and manipulation in different software. The next practical will provide much more detail on R, so don't worry.
In RStudio go:
1. File > New File > R Script
You should be able to see these quadrants (without the code):
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/RStudio.png')
```
Below are bits of code, to start we will work using the **console**. So just copy the bits of code into the console window, changing the file names to where your data is stored. Then at the end of this section I'll show you how to make a script.
R works on packages that are collections of functions and data. For this practical we will need the ones listed in the code chunk below. Whilst we've installed them (with the code below), we haven't yet loaded them. It's best practice to do all this at the start of your code, however, for demonstration purposes I'll load each one as we need it.
```{r, message=FALSE, warning=FALSE, eval=FALSE, cache=TRUE}
install.packages(c("sf", "tmap", "tmaptools", "RSQLite", "tidyverse"), repos = "https://www.stats.bris.ac.uk/R/")
```
Packages we've installed:
* ```sf```: simple features, standard way to encode spatial vector data
* ```tmap```: layer-based and easy approach to make thematic maps
* ```tmaptools```: set of tools for reading and processing spatial data
* ```RSQLite```: embeds the SQLite database engine in R
Here, `repos` stands for repository where we will download the packages from. Once you have set it, you shouldn't need to specify it again. Whilst we've installed the packages we haven't loaded them...this is done through using ```library()``` function. Thanks to [Dianne Cook](https://twitter.com/visnut) for this image...
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/install_library.jfif')
```
If you are **using a Mac** you might also need `rgdal`... this is because a lot of packages are dependent on it and it might not properly install...
```{r, message=FALSE, warning=FALSE, eval=FALSE, cache=TRUE}
install.packages("rgdal")
```
Then load `rgdal`...
```{r, message=FALSE, warning=FALSE, eval=FALSE, cache=TRUE}
library(rgdal)
```
If you still have issues the check out the [Mac R issues] section
#### Load data
Load the ```sf``` package so we can read our shapefile in --- remember to change to filepath to your shapefile.
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/sf.png')
```
For this first practical we'll just leave the data where it is, next week we'll show you how to use projects to make calling data much easier.
> **Note** by default in R, the file path should be defined with ```/``` but on a windows file system it is defined with ```\```. Using ```\\``` instead allows R to read the path correctly – alternatively, just use ```/```
```{r, message=FALSE, warning=FALSE, cache=TRUE}
library(sf)
# change this to your file path!!!
shape <- st_read("Prac1_data/statistical-gis-boundaries-london/ESRI/London_Borough_Excluding_MHW.shp")
```
> **Note** If you are working on RStudio cloud and have a shapefile (along with all the other relevant files required) you will just need to use...
```{r, message=FALSE, warning=FALSE, cache=TRUE, eval=FALSE}
shape <- st_read("London_Borough_Excluding_MHW.shp")
```
As RStudio cloud knows you have setup a project and to look for files within it...we cover this very soon for RStudio desktop.
To get a summary of the data held within the shapefile data (attribute table) enter the following:
```{r, cache=TRUE}
summary(shape)
```
To have a quick look what the shapefile looks like enter the following:
```{r, cache=TRUE}
plot(shape)
```
That plots everything in the shapefile (all the attitbues) if you just wanted the geometry (outline of the shape) you could use...
```{r}
plot(sf::st_geometry(shape))
```
From what we did in QGIS and ArcMap this should look familiar.
We now need to load our ```.csv``` file:
```{r, cache=TRUE, warnings=FALSE, messages=FALSE}
library(tidyverse)
mycsv <- read_csv("Prac1_data/fly_tipping_borough_edit.csv")
```
When you load `tidyverse` you might get a list of conflicts, this basically means that several packages have functions named the same thing. For example there is a function named `filter()` in the packages `dplyr` and `stats`. If you wanted to use the `dplyr` version you would use `dplyr::filter()` or for the `stats` version it would be `stats::filter()`...
To view the data just input:
```{r cache=TRUE, warnings=FALSE, messages=FALSE}
mycsv
```
#### Join data
In R we've given our London boroughs shapefile the name shape and our flytipping ```.csv``` the name mycsv. If you look in the Environment quadrant you should see them both listed.
Join the ```.csv``` to the shapefile. Here, replace Row Labels with whatever your GSS_CODE is called in the ```.csv```:
```{r, cache=TRUE}
library(tmaptools)
shape<-merge(shape, mycsv, by.x="GSS_CODE", by.y="Row Labels")
```
Let's break this down a bit. We just created a tibble of mycsv (this is a new form of a dataframe) where each column has a variable and each row contains a set of values --- so basically a normal table. The match simply found the GSS_CODE values in the ```.csv``` and joined the data to our shapefile.
Check the merge was successful, this is just going to show the top 10 rows:
```{r cache=TRUE}
head(shape, n=10)
```
Now, let's make a quick thematic map (or a qtm) using the package ```tmap ```. I've made mine for flytipping between 2011 and 2012 (column 2011_12). But check what your coloumn name is from the adove code `head(shape, n=10)` it might be slightly different like 2011-2012 or x2011_2012....
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/colname.png')
```
```{r cache=TRUE}
library(tmap)
tmap_mode("plot")
# change the fill to your column name if different
qtm(shape, fill = "2011_12")
```
### Export data
Finally write shape to a new GeoPackage (```.gpkg```) giving it the layer name of your choice:
```{r cache=TRUE}
st_write(shape, "Prac1_data/Rwk1.gpkg", "london_boroughs_fly_tipping", delete_layer=TRUE)
```
So here, we are saying the shape is the object we want to save, then to the GeoPackage file path, with the layer name of ```london_boroughs_fly_tipping```. I've set ```delete_layer``` to true so I could overwrite mine when I developed this practical. Changing it to false would generate an error message if you ever tried to re-run the code.
Let's also add the ```.csv``` as we did in QGIS. This is a bit more complicated as we have to use the SQLite database package. Firstly, connect to the ```.gpkg``` we just made:
```{r cahce=TRUE}
library(readr)
library(RSQLite)
con <- dbConnect(RSQLite::SQLite(),dbname="Prac1_data/Rwk1.gpkg")
```
Now examine what is in the ```.gpkg```...you can see that i've already got my ```original_csv``` stored within the ```.gpkg``` as when i developed this practical i made sure it was working!
```{r cache=TRUE}
dbListTables(con)
```
Add your ```.csv``` and disconnect from the ```.gpkg```:
```{r cache=TRUE}
dbWriteTable(con,"original_csv", mycsv, overwrite=TRUE)
dbDisconnect(con)
```
Here overwrite let's you well..overwrite the exisiting file...if this wasn't specified as true you would get an error saying the file already existed if you tried to run this code again.
#### Making a script
To convert this bit of analysis into a script that we could save and run again in future, I would write the following in the script quadrant:
```{r, eval=FALSE, cache=TRUE}
library(sf)
library(tmap)
library(tmaptools)
library(RSQLite)
library(tidyverse)
#read in the shapefile
shape <- st_read(
"Prac1_data/statistical-gis-boundaries-london/ESRI/London_Borough_Excluding_MHW.shp")
# read in the csv
mycsv <- read_csv("Prac1_data/fly_tipping_borough_edit.csv")
# merge csv and shapefile
shape <- merge(shape,
mycsv,
by.x="GSS_CODE",
by.y="Row Labels")
# set tmap to plot
tmap_mode("plot")
# have a look at the map
qtm(shape, fill = "2011_12")
# write to a .gpkg
st_write(shape, "Prac1_data/Rwk1.gpkg", "london_boroughs_fly_tipping", delete_layer=TRUE)
# connect to the .gpkg
con <- dbConnect(SQLite(),dbname="Prac1_data/Rwk1.gpkg")
# list what is in it
dbListTables(con)
# add the original .csv
dbWriteTable(con,"original_csv", mycsv, overwrite=TRUE)
# disconnect from it
dbDisconnect(con)
```
You can then save your script through File > Save As.
If you are on a Mac you might also need to load `rgdal`...just add the following at the top of the script.
```{r, message=FALSE, warning=FALSE, eval=FALSE, cache=TRUE}
library(rgdal)
```
### What will I use
Well... it depends. If you wanted to quickly open a dataset to explore its contents then I'd use QGIS or ArcMap. However, if you had 100 raster images that you wanted to clip to your study area, I'd automate it in R. There are also specific packages developed for each type of software that might dictate what you use, for example I recently made use of the Urban Multi-scale Environmental Predictor (UMEP) plugin in QGIS. That said, as I needed to match different hourly meteorological variables over a three year period I automated the first part of the analysis in R and loaded a ```.csv``` into QGIS. Recent advancments have also closed the gap somewhat between Graphic User Interface (GUI) GIS software (such as QGIS) and programming languages (such as R) with 'bridges' that allow you to control GUI software through code. To learn more about these bridges read [Lovelace et al. (2019) chapter 9](https://geocompr.robinlovelace.net/gis.html#introduction-6).
## Data sources and task
Below I've listed a few good data sources. **For this week's task** explore these and any others you can find and get an interesting dataset (e.g. in this practical our flytipping ```.csv```) that you could join to some spatial data (e.g. in this practical the London boroughs ```.shp```). This could be for any location in the world.
### UK Data Service
The UK Data Service geography service (https://census.edina.ac.uk/) has a library of hundreds of current and former boundary datasets for which attribute data are produced in the UK.
### ONS
The Office for National Statistics (ONS) are the national statistical agency for England and Wales and have recently started to provide access to boundary data for the statistics they produce for various geographic areas.
Many of the boundaries on the [ONS Geoportal](http://geoportal.statistics.gov.uk/) are also available from the Edina Census Geography website in a more flexible fashion, however the ONS website provides very quick access to bulk-downloads --- something which can be very useful when reading data directly from the web using computer software. From the ONS website you can also extract the URL at which the data is stored to use directly within your future code...
### nomis
Nomis is provided by the ONS giving free access to UK labour market statistics. You can also [bulk download census data](https://www.nomisweb.co.uk/census/2011/bulk/r2_2) from the site too!
### OS
The Ordnance Survey (OS) are the national mapping agency for the UK. A few years ago, they opened up a number of their data products for public use including greenspace, OS Open Map and OS Terrain.
For the full range see: https://www.ordnancesurvey.co.uk/business-and-government/products/finder.html?Licensed%20for=OpenData%20(Free)&withdrawn=on
### Edina Digimap
Before the Ordnance Survey opened up much of its data for public use, academics and students in the UK could access OS data using the Edina Digimap Service --– this service is still available today and provides access to a number of products in addition to those available from OS Open Data.
Perhaps the most exciting of the additional OS data products available from Digimap is OS MasterMap. MasterMap is a framework for all OS data and contains layers of data that include details of real world objects such as buildings, roads, paths, rivers, physical structures and land parcels, as well as the complete UK transport network. Whilst we still are required to go through Edina OS have recently announced plans to make this dataset free in the near future under the new Geospatial Commission.
```{r echo=FALSE, out.width = "500pt", fig.align='center'}
knitr::include_graphics('prac1_images/mastermap.png')
```
### OSM
Open Street Map (OSM) is a fantastic resource --– as the name suggests, all data contained in Open Street Map are open and free for anyone to use. Much like Wikipedia, anyone can contribute content to OSM and this brings with it its own benefits (frequent updates, very large user-base) and problems (data quality and patch coverage). OSM is a very good example of Volunteered Geographic Information (VGI).
It’s possible to download OSM data straight from the website, although the interface can be a little unreliable (it works better for small areas). There are, however, a number of websites that allow OSM data to be downloaded more easily and are directly linked to from the ‘Export’ option in OSM. Geofabrik (https://www.geofabrik.de/data/download.html) allows you to download frequently updated Shapefiles for various global subdivisions.
### DEFRA
The Department for Environment and Rural Affairs (DEFRA) have recently created the Data Services Platform to openly distribute environmental data. See: https://environment.data.gov.uk/
### Data lists
Another good place to start searching for data are data lists. They simply provide a comprehensive overview of all available data conveniently categorised by discipline and country.
I normally use this one: https://freegisdata.rtwilson.com/
## Summary
Within this practical we have explored the different types, formats and software used to store, analyse and manipulate spatial data. In reflecting upon this practical you should consider the (dis)advantages of each, where and when they might be appropriate and the overall practicality. Next week we will delve further into R and RStudio.
## Feedback
Was anything that we explained unclear this week or was something really clear...let us know using the [feedback form](https://forms.gle/w2GUDYc7tSavGy7r6). It's anonymous and we'll use the responses to clear any issues up in the future / adapt the material.
## Mac R issues
If you have a Mac and run into issues using R, try this...
It seems that a lot of the packages are dependent on rgdal, which might not properly install...
**Order of operations**
1. Install java JDK (to respond to error Unable to find any JVMs matching version "(null)", which occurred when we tried to load `OpenStreetMap` package in RStudio)
2. Download and install the appropriate `.dmg` from [Java SE Development Kit 11.0.1](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
3. Run sudo R CMD javareconf in Terminal as described [here](http://conjugateprior.org/2014/12/r-java8-osx/)(though don't follow this tutorial exactly, just up to that terminal command).
4. (Maybe) restart your computer (not really sure when this is necessary).
**Install GDAL**
GDAL, the Geospatial Data Abstraction Library, appears to be a massively important package / library / whatever that a lot of the spatial tools we use depends on. This is where things might be sticky --- we already installed GDAL for QGIS, but obviously RStudio can't find that install ... dunno how to update the pointers, but we found that installing GDAL (again?) solved it. We HOPE that this didn't ruin or break any other software we've installed, only time will tell :grimacing:
6. To install GDAL on a mac, first (if you haven't) install [homebrew](https://brew.sh/), the mac package manager
This can be done by executing `/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"` in Terminal, inputting password etc.
7. Now we're ready to brew install gdal (also in Terminal), which will run through and install a massive list of dependencies etc.
**Set up RStudio**
8. Restart RStudio (if the following doesn't work on first go...)
9. Run through all the `install.packages()` commands one by one in RStudio and check to make sure that they install.
10. Check if `rgdal` package is working.
11. Check the other packages `OpenStreetMap`, `tmap`, etc.