forked from taniaguerrero/CASA0005repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08-prac8.Rmd
1250 lines (885 loc) · 55.1 KB
/
08-prac8.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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Online mapping / descriptive statistics
This practical is formed of two parts, you can pick one you are more intersted in or complete both.
Part A looks at some more spatial descriptive statistics
Part B looks focuses on online mapping
## 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**
From weeks 6-9, learn and practice analysis from the course and identify appropriate techniques (from wider research) that might be applicable/relevant to your data. Conduct an extensive methodological review – this could include analysis from within academic literature and/or government departments (or any reputable source).
:::
::: {.infobox .note data-latex="{note}"}
**Reading**
* For k-means clustering and exploratory data analysis read [Chapter 12 "K-Means Clustering"](https://bookdown.org/rdpeng/exdata/k-means-clustering.html) from Exploratory Data Analysis with R by Peng (2016).
* For interative maps re-read [Chapter 8: "Making maps with R"](https://geocompr.robinlovelace.net/adv-map.html) Geocomputation with R by Lovelace, Nowosad and Muenchow (2020), especially setion 8.4.
If you want to learn more about Shiny applications then [Chapter 2 "Your first Shiny app"](https://mastering-shiny.org/basic-app.html#introduction) from Mastering Shiny
by Wickham.
Remember this is just a starting point, explore the [reading list](https://rl.talis.com/3/ucl/lists/139FBAF8-DACD-60FB-8BDC-E9C9E09BA885.html?lang=en-GB&login=1), practical and lecture for more ideas.
:::
## 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=6Bh6IL1mNfc)
[Adam](https://open.spotify.com/track/3BGF4XAm8jaEi2LcGR57O3?si=gfYc6LS6Tgy9M9oXVVG4SQ)
Bit different from me this week - I'm not all about drum and bass (although I mostly am). Stumbled across these recently and I should have known about them for much longer. The Joy Formidable - this is a 10th Anniversary revisit of their first EP and is ace. If you like Welsh, you're in for a treat!
## Part A spatial descriptive statistics
### Learning objectives
By the end of this practical you should be able to:
1. Create descriptive plots (histograms and boxplots) to help understand the frequency distributions of your data
2. Write custom functions to process your data
3. Produce a location quotient map to highlight interesting (above and below average) patterns in your data
4. Write a function in R to produce a range of different maps based on user inputs
5. Perform a very basic cluster analysis and output the results of a basic geodemographic classification
### Getting Started
Before we begin this week’s practical, we need to load our packages and carry out some data preparation...
```{r prac8_load, message=FALSE}
library(highcharter)
library(tidyverse)
library(downloader)
library(rgdal)
library(sf)
library(ggplot2)
library(reshape2)
library(plotly)
library(raster)
library(downloader)
library(rgdal)
```
There is a problem with our London Wards data --- we are missing some data relating to housing tenure. The housing tenure data in this file comes from the 2011 Census and visiting http://www.nomisweb.co.uk/ and interrogating Table KS402EW (the Tenure table), we can discover that data for the percentage of shared owners and those living in accommodation rent free are missing.
Rather than making you go off to Nomisweb and fetch this data, because I'm really nice, I've posted on GitHub a file containing this and extra categorical, ratio and geographical data that we will need to add to our existing London data file.
We can easily join this new data to our original data in R.
```{r prac8_read_data}
getwd()
LondonWards <- readOGR("prac8_data/NewLondonWard.shp", layer="NewLondonWard")
# convert to sf
LondonWardsSF <- st_as_sf(LondonWards)
extradata <- read_csv("prac8_data/LondonAdditionalDataFixed.csv")
LondonWardsSF <- merge(LondonWardsSF, extradata, by.x = "WD11CD", by.y = "Wardcode")
```
### Main Tasks
### Task 1 - Descriptive Statistics
Using the lecture notes for guidance, you should generate the following graphs and descriptive statistics using standard functions and ggplot2 in R. Each element should be copied and saved to a word document or something similar:
Generate the following from your LondonWardsSF data frame (*hint, use the code in the lecture notes to help you if you are unsure how to do this*):
* A simple histogram for a scale/ratio variable of your choice
* A simple histogram for a scale/ratio variable of your with a different frequency bin-width
+ The same histogram with vertical lines for the mean, median and mode (the mode will be the mid value for the bin with the largest count) and the inter-quartile range. *hint – use summary(table$variable) to find the values if you are not sure*
+ The same histogram with three different kernel density smoothed frequency gradients
* A boxplot of the same variable
* A faceted grid of histograms with for every variable in your London Wards data file. In order to do this, you will need to remove Factor (non-numeric) variables from your dataset and re-shape your data using the `melt()` function in the `reshape2` package (hint – check the help file for `melt.data.frame()` to understand what the code below is doing). The code below will help you:
```{r prac8_data_manipulate, message=FALSE, warning=FALSE}
#check which variables are numeric first
list1 <- as.data.frame(cbind(lapply(LondonWardsSF, class)))
list1 <- cbind(list1, seq.int(nrow(list1)))
#you will notice that there are some non-numeric columns, we want to exclue these, and drop the geometry
LondonSub <- LondonWardsSF[,c(1:73,83:86)]
#make sure the geometry is null or we will get errors - also create some subsets so that we can see our data better
LondonSub2 <- st_set_geometry(LondonWardsSF[,c(1:3,9:27)],NULL)
LondonSub3 <- st_set_geometry(LondonWardsSF[,c(1:3,28:50)],NULL)
LondonSub4 <- st_set_geometry(LondonWardsSF[,c(1:3,51:73,85:86)],NULL)
LondonMelt2 <- melt(LondonSub2, id.vars = 1:3)
attach(LondonMelt2)
hist2 <- ggplot(LondonMelt2, aes(x=value)) + geom_histogram(aes(y = ..density..)) + geom_density(colour="red", size=1, adjust=1)
hist2 + facet_wrap(~ variable, scales="free")
LondonMelt3 <- melt(LondonSub3, id.vars = 1:3)
attach(LondonMelt3)
hist3 <- ggplot(LondonMelt3, aes(x=value)) + geom_histogram(aes(y = ..density..)) + geom_density(colour="red", size=1, adjust=1)
hist3 + facet_wrap(~ variable, scales="free")
LondonMelt4 <- melt(LondonSub4, id.vars = 1:3)
attach(LondonMelt4)
hist4 <- ggplot(LondonMelt4, aes(x=value)) + geom_histogram(aes(y = ..density..)) + geom_density(colour="red", size=1, adjust=1)
hist4 + facet_wrap(~ variable, scales="free")
```
Make a note of which variables appear normally distributed and which appear to be skewed. What do the histograms for nominal and ordinal data look like?
Try performing a log10() transformation on the x variables and plotting a similar facet grid of histograms – what does this do to some of the skewed variables? For example, with the last subset:
```{r prac8_hist}
hist5 <- ggplot(LondonMelt4, aes(x=log10(value))) + geom_histogram(aes(y = ..density..)) + stat_function(fun=dnorm, colour="red", size=1)
hist5 + facet_wrap(~ variable, scales="free")
```
* Create a 2D histogram and 2D kernel density estimate of ward centroids in London using the Eastings and Northings data in the x and y columns of your dataset. For example:
```{r prac8_ggplot}
londonpoint<-ggplot(LondonSub, aes(x=x.y,y=y.y))+geom_point()+coord_equal()
londonpoint
londonpoint<-ggplot(LondonSub, aes(x=x.y,y=y.y))+stat_bin2d(bins=10)
londonpoint
londonpoint<-ggplot(LondonSub, aes(x=x.y,y=y.y))+geom_point()+coord_equal()
londonpoint
londonpoint+stat_density2d(aes(fill = ..level..), geom="polygon")
```
### Extension 1
If you really want to go down the road of carrying out KDE in a range of different ways, then this is an excellent place to start: http://egallic.fr/R/sKDE/smooth-maps/kde.html --- perhaps try it with some of the Blue Plaques data from previous weeks.
### Task 2 - Introduction to functions in R
One of the great strengths of R is that is lets users define their own functions. Here we will practice writing a couple of basic functions to process some of the data we have been working with.
One of the benefits of a function is that it generalises some set of operations that can then be repeated over and again on different data.
In the lecture, it was mentioned that sometimes we should recode variables to reduce the amount of information contained in order that different tests can be carried out on the data. Here we will recode some of our scale/ratio data into some nominal/weak-ordinal data to carry out some basic analysis on.
There are various online guides which will help you a little more in writing functions, but the structure of a function in R is given below:
```{r prac8_fun,eval=FALSE}
myfunction <- function(arg1, arg2, ... ){
statements
return(object)
}
```
A function to recode data in our dataset might look like the one below:
```{r, prac8_fun2, eval=T}
newvar<-0
recode<-function(variable,high,medium,low){
newvar[variable<=high]<-"High"
newvar[variable<=medium]<-"Medium"
newvar[variable<=low]<-"Low"
return(newvar)
}
```
### What's going on in this function?
* First we initialise a new variable called `newvar` and set it to = 0. We then define a new function called `recode`. This takes in 4 pieces of information: A variable (called `variable` but I could have called it anything) and three values called `high`, `medium` and `low`. It outputs a value to the new string variable `newvar` based on the values of high, medium and low that are given to the function.
* To create the function in R, highlight the all of the code in the function and then run the whole block (ctrl-Return in R-Studio). You will see that the function is stored in the workspace.
* We can now use this function to recode any of our continuous variables into high, medium and low values based on the values we enter into the function.
* We are going to recode the Average GCSE Score variable into High, Medium and Low values – High will be anything above the 3rd Quartile, Low will be anything below the 1st Quartile and Medium – anything in between.
*Note, if your data doesn't have the 2013 GCSE scores but 2014, it will have different figures to these figures below and you will need to call the column by the column header you have*
```{r prac8_attatch, message=FALSE, warning=FALSE}
attach(LondonWardsSF)
#Check the name of your column, there could be a slight error and it might be called 'AvgGCSED201'
summary(AvgGCSE201)
```
Create a new column in your data frame and fill it with recoded data for the Average GCSE Score in 2013. To do this, pass the AvgGCSE2013 variable to the `recode()` function, along with and the three values for high, medium and low. You should create a new variable called gcse_recode and use the function to fill it with values
If you wanted to be really fancy, you could try altering the function to calculate these “High”, “Medium” and “Low”
```{r prac8_recode}
LondonWards$GCSE_recode <- recode(AvgGCSE201,409.1,358.3,332.3)
#or
LondonWardsSF$GCSE_recode <- recode(AvgGCSE201,409.1,358.3,332.3)
```
You should also create a second re-coded variable from the unauthorised absence variable using the same function – call this variable unauth_recode and again, used the 3rd and 1st quartiles to define your high, medium and low values.
Make sure these are saved to your data frame as we will use these in next week’s practical.
On to another function. This time, we will calculate some location quotients for housing tenure in London. If you remember, a location quotient is simply the ratio of a local distribution to the ratio of a global distribution. In our case, our global distribution will be London.
```{r prac8_LQ}
#Location Quotient function 1
LQ1<-function(pctVariable){
pctVariable /mean(pctVariable)
}
#Location Quotient function 2
LQ2<-function(variable,rowtotal){
localprop<-variable/rowtotal
globalprop<-sum(variable)/sum(rowtotal)
return(localprop/globalprop)
}
```
The two functions above calculate the same Location Quotient, but the first one works on variables which have already been converted into row percentages, the second will work on raw variables where an additional column for the row totals is stored in a separate column – e.g. “age 0-15”, “age 16-64” and “age 65 plus” all sum to the “Pop2013” column in our data London Wards data set:
```{r prac8_head}
head(LondonWardsSF[,1:7])
```
Calculate Location Quotients for the 5 Housing tenure variables (Owner Occupied, Private Rent, Social Rent, Shared Ownership, Rent Free) in your data set using either of the functions above. Save these as 5 new variables in your dataset. *Hint – use the function to create the variable directly, for example:
```{r prac8_df, eval=FALSE}
#this is pseudo code, but you should see how this works
dataframe$newLQVariable <- LQ1(originalPercentageVariable)
#or
dataframe$newLQVariable <- LQ2(originalVariable,rowTotalVariable)
```
```{r prac8_cols, include=FALSE}
#note, you will probably need to change the column headers of the columns you are referring to here
attach(LondonWardsSF)
summary(LondonWardsSF$UnauthAbse)
LondonWardsSF$unauth_recode <- recode(UnauthAbse,2.4657,1.4105,0.8215)
LondonWardsSF$LQOwned <- LQ1(PctOwned20)
LondonWardsSF$LQSocRe <- LQ1(PctSocialR)
LondonWardsSF$LQPriRe <- LQ1(PctPrivate)
LondonWardsSF$LQShare <- LQ1(PctSharedOwnership2011)
LondonWardsSF$LQRentF <- LQ1(PctRentFree2011)
```
### Task 3 – Mapping Location Quotients
You should now try and create a map or series of maps of your housing tenure location quotients using `tmap` or `ggplot` – you have two options to try and accomplish this:
#### Easy option
Create a map by referring back earlier practicals in this course and follow the steps from there (or, indeed, use your memory)
#### Double hard option
If you want to blow your mind, try the function below **Warning**, I wrote this myself, so the code is pretty untidy and relies on the input data to already be in the form of row percentages.
The function will take in a variable, calculate a location quotient for it, map it and then save the map as a PNG to your working directory. This is the sort of thing that you could produce for the coursework if you really got stuck into learning R...
Creating the maps using it is the easy bit, but see if you can figure out from my code what’s going on and what the function is doing at each stage! Here there are functions inside a function, so it gets a little complex.
You should, however, be able to Copy the code into R, run the whole function and then test it out and produce a map like the one below:
```{r prac8leaf, message=FALSE, warning=FALSE, cache=FALSE}
#############################################################
##A Function for creating various location quotient maps
##
##By Adam Dennett October 2014 - updated November 2018
##
##Please note, this function requires input data to already be in ##the form of row percentages. To create the function, highlight the ##whole block of code and run it. To run the function, simply use ##LQMapper(your_dataframe)
library(rgeos)
library(ggplot2)
library(maptools)
library(sf)
library(sfc)
library(tmap)
sfdataframe <- LondonWardsSF
LQMapper<-function(sfdataframe){
print(colnames(sfdataframe))
vars<-readline("From the list above, select the variables
you want to calculate location quotients for
separated by spaces...")
# split the string at the spaces
vars<-unlist(strsplit(vars, split = "\\s"))
# now save vars as a list
vars<-as.list(vars)
print("looping to create new location quotient variables...")
attach(sfdataframe)
for(i in 1:length(vars)){
pctVariable<-vars[[i]]
colvect<-which(colnames(sfdataframe)==vars[[i]])
#this is a little function to calculate location quotients
LQ<-function(pctVariable){
pctVariable/mean(pctVariable)
}
#use LQ function here to create new variable in sfdataframe
#and save it
v <- sfdataframe[,colvect]
sfdataframe[,paste("LQ_",pctVariable, sep="")] <- LQ(v[[pctVariable]])
}
#reset i as we're going to use it again in a minute
i=0
print("now entering the plotting loop")
for(i in 1:length(vars)){
print("I'm plotting")
pctVariable<-paste("LQ_",vars[[i]],sep="")
colvect<-which(colnames(sfdataframe)==paste("LQ_",vars[[i]],sep=""))
#create the plot
LQMapperPlot <- tm_shape(sfdataframe) + tm_polygons(pctVariable,
style="jenks",
palette="Spectral",
midpoint=1,
title=pctVariable,
alpha = 0.5)
LQMapperPlot
#save the plot to a pdf and give it a name based on its variable
tmap_save(LQMapperPlot, filename=paste(pctVariable,".png",sep=""))
}
return(dataframe)
}
###################################################################
```
```{r prac8_LQmapper, eval=FALSE}
#run the function by calling it and putting in the data frame parameter - at several points you will be asked for some user input
LQMapper(LondonWardsSF)
```
### Extension 2
Clearly there are lots of things that can be done to improve this function, it's plotting, legend, layout etc. - feel free to experiment and customise
### Task 4 – Creating a Basic Geodemographic Classification
As we saw in the lecture, geodemographic classifications are widely used to classify areas according to the characteristics of the population that inhabits them. All geodemographic classifications are created using cluster analysis algorithms. Many of these algorithms exist, but one of the most commonly used is k-means.
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_1.jpg')
```
One of the pitfalls of these algorithms is that they will always find a solution, whether the variables have been selected appropriately or standardised correctly. This means that it’s very easy to create a classification which is misleading.
All of that said, it is useful to see how straightforward it is to create a classification yourself to describe some spatial data you have.
In a cluster analysis, you should select variables that are:
* Ranged on the same scale
* Normally distributed
* Not highly correlated
To make this task easier, we will just select two variables to make our classification from. In a real geodemographic classification, hundreds of variables are often used.
```{r prac8_cluster}
LondonWardsDF <- st_set_geometry(LondonWardsSF, NULL)
#display list of variables
cbind(lapply(LondonWardsDF, class))
#clustering
# Create a new data frame just containing the two variables we are #interested in
mydata<-as.data.frame(LondonWardsDF[,c("PctOwned20","PctNoEngli")])
attach(mydata)
#– check variable distributions first
histplot <- ggplot(data=mydata, aes(x=PctOwned20))
histplot +geom_histogram()
histplot <- ggplot(data=mydata, aes(x= PctNoEngli))
histplot +geom_histogram()
```
Let's make our k-means find 3 clusters with 25 iterations. The graphics below by [Allison Horst](https://twitter.com/allison_horst) will help explain the process...
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_2.jpg')
```
```{r}
fit <- kmeans(mydata, 3, nstart=25) # 3 cluster solution
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_3.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_4.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_5.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_6.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_7.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_8.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_9.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_10.jpg')
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_11.jpg')
```
Now let's get out cluster means, plot them and then add them to our London wards...
```{r}
# get cluster means
centroid<-aggregate(mydata,by=list(fit$cluster),FUN=mean)
#print the results of the cluster groupings
centroid
# as we only have variable two dimensions we can plot the clusters on a graph
p <- ggplot(mydata,aes(PctOwned20, PctNoEngli))
p+geom_point(aes(colour=factor(fit$cluster)))+geom_point(data=centroid[,2:3],aes(PctOwned20, PctNoEngli), size=7, shape=18)+ theme(legend.position="none")
mydata$cluster <- fit$cluster
#add the cluster groups to the LondonWards data frame
LondonWardsSF$cluster<-mydata$cluster
#merge the cluster results into a fortified dataframe for plotting (we made LondonGeom earlier)
#London_geom<-merge(London_geom,LondonWardsDF,by.x="id", by.y="Wardcode1")
#now map our geodeomographic classification
map <- ggplot(LondonWardsSF) + geom_sf(mapping = aes(fill=cluster))+scale_fill_continuous(breaks=c(1,2,3))
map
```
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/kmeans_12.jpg')
```
Now of course this is just the most basic of classifications, but you can easily see how you could include more variables or different variables to create a different classification - this is perhaps something you could try.
I haven't even gone into using different clustering algorithms, how to decide on the appropriate number of clusters, using silhoutte plots to assess the strength of the clusters or creating pen-portraits using the variable z-scores for each cluster - this is practically a whole course in its own right... or indeed a dissertation topic!
## Part B Online mapping
### Learning objectives
By the end of this practical you should be able to:
1. Descrbie and explain different methods for producing online maps
2. Create interative maps using RPubs, RMarkdown site generator and Shiny
3. Critically appraise the appropriateness of mapping technqiues based on the dataset and purpose of the output map
### Introduction
In this practical we are going to preliminary stages of a mini-investigation. Since 2015 the law has capped short-term lets in London at 90 nights per year. However, this is very hard to enforce due to a lack of data and extensive evidence required to prove that the limit has been exceeded. This has been recently reflected in the [Housing Research Note 2020/04: Short-term and holiday letting in London](https://www.london.gov.uk/sites/default/files/housing_research_note_4-_short-term_and_holiday_letting_in_london.pdf) by the Greater London Authority (GLA):
>"there are signs that short-term letting platforms are becoming increasingly commercialised and there are concerns that removing housing supply from the market to offer it for short-term letting could be exacerbating London’s housing shortage."
The author, Georgie Cosh, was also kind enough to share some of the code used for this report. Guess what! They used R! Have a look at their code in the R file called GLA_airbnb_analysis in the prac8_data folder.
Whilst Air bnb have implemented a system the removes listings once they have been rented for 90 days per year unless an appropraite permit is in place we want to interactively visualise the the number of air bnb lettings (and hotels for comparison) per borough as a starting point. This could then be used to undertake further investigation into boroughs with high short term lets, for example exploring other websites to see if the properties are listed and jointly exceed 90 days or optimising localised monitoring. As these rules only apply to entire homes we will only extract only these, and for monitoring purposes (e.g. random annual inspections) those are availbale for 365 days of the year.
We will now explore several ways to do this...
::: {.infobox .tip data-latex="{note}"}
The report by Cosh (2020) goes a bit further than this and implements an occupancy model (based on a number of assumptions) to estimate the number of nights a Air bnb is rented out for, so check it out, perhaps an idea for your final project.
:::
### RPubs
One of the most straight forward publishing tools is RPubs. It takes an ```.Rmd``` and directly uploads it to rpubs.com --- all files are publically available on this website.
1. To start with you need to make a free account. Go to: https://rpubs.com/users/new and register
2. Create a new project in RStudio and open a new R Markdown file (File > New File > R Markdown)
3. You'll see that the file is automatically populated with some information, have a read through it then click the Knit icon ...
```{r prac8_knitt, echo=FALSE, out.width = "800pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/knitt.png')
```
4. Let's make some changes to your ```.Rmd```. Delete all the text and code except from header inforamtion (that is enclosed by three dashes at the top of the file)
5. Insert a new code chunk (go back to [RMarkdown] if you need a refresher)...
```{r echo=FALSE, out.width = "450pt", fig.align='center', cache=TRUE}
knitr::include_graphics('allisonhorst_images/rmarkdown_wizards.png')
```
...Add add some code of your choice from either a previous practical or your own work. As it's a new project you'll have to either copy the data into your project folder or set the working directory ```setwd()```. If it's all online data that you've loaded directly from the web into R, this shouldn't be an issue. I'm going to use the interactive map we made in practical 5 (the [Advanced interactive map] section).....Here is the code i've put in my chunk:
```{r prac8_airbnb_hotel, warnings=FALSE, message=FALSE, cache=FALSE, eval=FALSE}
library(sf)
library(tmap)
library(leafpop)
library(leaflet)
library(tmaptools)
library(tidyverse)
library(plyr)
OSM <- st_read("data/gis_osm_pois_a_free_1.shp")
Londonborough <- st_read("data/London_Borough_Excluding_MHW.shp")
Airbnb <- read_csv("data/listings.csv")
# plot xy data
Airbnb <- st_as_sf(Airbnb, coords = c("longitude", "latitude"),
crs = 4326)
# reproject
OSM <- st_transform(OSM, 27700)
Airbnb <- st_transform(Airbnb, 27700)
# we don't need to reproject Londonborough, but it
# doesn't have a CRS..you could also use set_crs
# it needs to have one for the next step
Londonborough<- st_transform(Londonborough, 27700)
#select hotels only
OSM <- OSM[OSM$fclass == 'hotel',]
# this bit of code would reduce our Airbnb data
# to entire places and available all year
Airbnb <- Airbnb[Airbnb$room_type == 'Entire home/apt' &
Airbnb$availability_365=='365',]
# make a function for the join
# functions are covered in practical 7
# but see if you can work out what is going on
# hint all you have to do is replace data1 and data2
# with the data you want to use
Joinfun <- function(data1, data2) {
# join OSM and London boroughs
joined <- st_join(data1, data2, join = st_within)
# count the number of hotels per borough
countno <- as.data.frame(count(joined$GSS_CODE))
# join the count back to the borough layer
counted <-left_join(data2, countno, by=c("GSS_CODE"="x"))
return(counted)
}
# use the function for hotels
Hotels <- Joinfun(OSM, Londonborough)
# then for airbnb
Airbnb <- Joinfun(Airbnb, Londonborough)
# now try to arrange the plots with tmap
breaks = c(0, 5, 12, 26, 57, 286)
#change the column name from freq for the legend
colnames(Hotels)[colnames(Hotels)=="freq"] <- "Accom count"
#join data
ti<-st_join(Airbnb, Hotels)
ti<-st_transform(ti,crs = 4326)
#remove the geometry for our pop up boxes to avoid
#the geometry field
ti2<-ti
st_geometry(ti2)<-NULL
popairbnb=popupTable(ti2, zcol=c("NAME.x", "GSS_CODE.x", "freq"))
pophotels=popupTable(ti2, zcol=c("NAME.x", "GSS_CODE.x", "Accom count"))
tmap_mode("view")
# set the colour palettes using our previously defined breaks
pal <- colorBin(palette = "YlOrRd", domain=ti2$freq, bins=breaks)
pal2 <- colorBin(palette = "YlOrRd", domain=ti2$`Accom count`, bins=breaks)
map<- leaflet(ti) %>%
# add basemap options
addTiles(group = "OSM (default)") %>%
addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addProviderTiles(providers$CartoDB.Positron, group = "CartoDB")%>%
#add our polygons, linking to the tables we just made
addPolygons(color="white",
weight = 2,
opacity = 1,
dashArray = "3",
popup = popairbnb,
fillOpacity = 0.7,
fillColor = ~pal(freq),
group = "Airbnb")%>%
addPolygons(fillColor = ~pal(`Accom count`),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
popup = pophotels,
fillOpacity = 0.7,group = "Hotels")%>%
# add a legend
addLegend(pal = pal2, values = ~`Accom count`, group = c("Airbnb","Hotel"),
position ="bottomleft") %>%
# specify layers control
addLayersControl(
baseGroups = c("OSM (default)", "Toner", "Toner Lite", "CartoDB"),
overlayGroups = c("Airbnb", "Hotels"),
options = layersControlOptions(collapsed = FALSE)
)
# plot the map
map
```
6. Add some text at the start of your ```.Rmd``` you can include titles and subtitle using # followed by a space, a second level subtitle would be ##, and third ###
```{r prac8_titles, warnings=FALSE, message=FALSE, cache=FALSE, eval=FALSE}
# Title
## Second sub title
### Third sub title
```
7. Save the file, Knitt it to HTML, this should be default and specified in the header --- enclosed by three dashes.
8. Once knitted you can easily publish the file to Ppubs using the Publish icon either in the viewer pane or the toolbar area (by run)
```{r prac8_publish, echo=FALSE, out.width = "200pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/publish.png')
```
Now how about adding a few design features...i've changed my header section to...
```{r prac8_header, eval=FALSE}
---
title: "publishexample"
output:
html_document:
theme: yeti
smart: true
highlight: textmate
toc: true
number_sections: true
toc_float:
collapsed: false
smooth_scroll: true
---
```
9. Knit and then publish again...you'll notice a few aesthetic changes
10. To learn more about these go explore:
* https://bookdown.org/yihui/rmarkdown/html-document.html
* http://www.datadreaming.org/post/r-markdown-theme-gallery/
* https://cran.r-project.org/web/packages/prettydoc/vignettes/architect.html
And for more code chunk control..
* https://bookdown.org/yihui/rmarkdown/r-code.html
* https://rmarkdown.rstudio.com/lesson-3.html
### RMarkdown site generator
#### Set the file structure
RPubs are useful but what if you wanted to make a full site with different tabs for introduction, methodology, results and recommedations...one way is to use the RMarkdown site generator hosted on GitHub
RMarkdown site generator is useful as it does not require any third-party add ons like blogdown which is reliant on the hugo site generator
To make a site you'll need the following to be within your project:
(a) A configuration file with the filename ```_site.yml```
(b) An ```index.Rmd```
(c) Any other ```.Rmd``` files you want to create into pages on the site
For the site to work you only require (a) and (b)....but that would be a pretty boring site...
11. In your new project add two new RMarkdown files called:
* ```_site.yml```
* ```index.Rmd```
```{r prac8_sitegenerator, echo=FALSE, out.width = "500pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/rsitegenerator.png')
```
12. In the ```_site.yml``` remove all code and add the following
```{r prac8_yml, eval=FALSE, message=FALSE, warning=FALSE, cache=FALSE}
name: "Hello world"
output_dir: "."
navbar:
title: "My example website"
left:
- text: "Home"
href: index.html
- text: "About"
href: publishexample.html
```
#### Link to GitHub
There are two ways to do this....
##### GitHub first
This is the 'easy' way as you woould repeat the steps in [Practical 4][Git, GitHub and RMarkdown] by firstly making a new repository on GitHub then loading a new project in RStudio, linking that to GitHub and copying all your files into your new project from the exisiting one.
##### GitHub last
So if you already have a RStudio project...like we do...we can link this to GitHub but the steps are a bit more invovled and there are several ways to acheive it --- as with most things in R.
13. Make a Git repo in RStudio. Go to Tools > Project Options > Git/SVN and select Git under Version control system and initialize a new repository, then restart RStudio. The Git tab should appear..
14. Next we need to make a new repository on GitHub. Go to GitHub, login and make a new repository. Make sure that it is **empty** with no README.. you should have something similar to this appear:
```{r prac8_newrepo, echo=FALSE, out.width = "800pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/gitnewrepo.png')
```
15. Clone the repository by copying the HTTPS
```{r prac8_HTTPS, echo=FALSE, out.width = "700pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/HTTPS.png')
```
16. Make one local commit. Under the Git tab > Diff > Stage the files > Add a commit message and click commit
17. Now we need to connect our local repository to the GitHub one. So Under the Git tab you'll the new brach button (two purple boxes linked to a white box)...
```{r prac8_addremote, echo=FALSE, out.width = "400pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/addremote.png')
```
18. Click it > Add Remote. Paste in the URL use the remote name origin and the branch name of master --- which you can get from the GitHub Quick setup screen after creating your repo. Check sync the branch with the remote > click create then select overwrite
```{r prac8_addremote2, echo=FALSE, out.width = "400pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/addremote2.png')
```
19. Push the files to your GitHub and they will appear on your GitHub repo
20. Next we need to actually build the site...there are a few ways to do this...Go to the Git tab you should see the Build tab, if you can't then go to Tools > Project Options > Build Tools and select website under Project build tools. Now click Build Website under the build tab
21. Alternatively you write the following in the console
```{r prac8_render_site, eval=FALSE, message=FALSE, warning=FALSE, cache=FALSE}
rmarkdown::render_site()
```
If you wanted to just build a page from your site --- say if you have made a rather big site with lots of analysis use:
```{r prac8_rendersite2, eval=FALSE, message=FALSE, warning=FALSE, cache=FALSE}
rmarkdown::render_site("index.Rmd")
```
22. Stage, commit and then push the files to your GitHub. I had some issues staging the ```site_libs``` folder in the Git tab. I fixed it by closing and reloading my R project then clicking the cog symbol (under Git tab) > Shell and typing ```git add .``` If you get an error message about the index file being locked... go and delete it and try again. If you can't delete restart the machine and try again. You will find it in the .git folder within your project. Once ```git add .``` runs you should see all the files staged, be able to commit and then push the changes to GitHub
Help:
* https://stackoverflow.com/questions/5834014/lf-will-be-replaced-by-crlf-in-git-what-is-that-and-is-it-important
* https://stackoverflow.com/questions/9282632/git-index-lock-file-exists-when-i-try-to-commit-but-cannot-delete-the-file
23. So your 'built' website is up on GitHub, but you need to tell it where to build the site from...Go to your GitHub repo > Settings, scroll down to GitHub pages and select the Source as the master branch
```{r prac8_githubpages, echo=FALSE, out.width = "800pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/GitHubpages.png')
```
24. Click on the link that is provided where your site is published and you should have a website with two tabs. Here is what mine looks like:
```{r prac8_markdownsite, echo=FALSE, out.width = "800pt", fig.align='center', cache=FALSE}
knitr::include_graphics('prac8_images/Markdownsite.png')
```
For more information on hosting your code from RStudio on GitHub check out the book [Happy Git and GitHub for the useR](https://happygitwithr.com/usage-intro.html)
My RMarkdown site can be found [here](https://andrewmaclachlan.github.io/PUBLISHEXAMPLE/), but note that i've added a Shiny tab...we'll cover Shiny next...
### Shiny
Shiny is an R package that lets you build interactive web apps, host them online and embed them within RMarkdown documents... have a [look at some examples](https://shiny.rstudio.com/gallery/)
To build a shiny you require three main *'items'* or blocks of code:
(a) Code that specfies the user interface or ```ui```
(b) Code that defines the server logic to plot variables (server function)
(c) A call to the ```ShinyApp``` function
These could either be within one large ```.R``` file or over several ```.R``` files.
25. Start a new R Project > New or existing directory > Shiny Web Application
26. Within your new R Project folder make a new folder called data and copy in the data we have been using
The main purpose of this part of the practical is to show you how to use Shiny so we won't make a Git repository.
27. Go File > New File > Shiny Web App
Here you can select either a single file or multiple file format, originally Shiny needed multiple files to run however in the latest version you can have this all in one script, i've just used one script here.
28. If you click Run App on either the ```app.R``` the example Shiny will load.
Now let's make one with our data...
#### Data preparation
29. The first part is easy and is based on analysis we have already compelted...we need to produce a ```sf``` multipolygon layer containing the number of hotels and airbnbs per London borough through....
```{r prac8_shiny, eval=TRUE, cache=FALSE, eval=FALSE}
# load packages
library(sf)
library(tmap)
library(leafpop)
library(leaflet)
library(tmaptools)
library(tidyverse)
library(plyr)
library(classInt)
# read in OSM
OSM <- st_read("data/gis_osm_pois_a_free_1.shp")
# read in Londonboroughs
Londonborough <- st_read("data/London_Borough_Excluding_MHW.shp")
# read in Airbnb
Airbnb <- read_csv("data/listings.csv")
# plot xy data
Airbnb <- st_as_sf(Airbnb, coords = c("longitude", "latitude"),
crs = 4326)
# reproject
OSM <- st_transform(OSM, 27700)
Airbnb <- st_transform(Airbnb, 27700)
# we don't need to reproject Londonborough, but it
# doesn't have a CRS..you could also use set_crs
# it needs to have one for the next step
Londonborough<- st_transform(Londonborough, 27700)
#select hotels only
OSM <- OSM[OSM$fclass == 'hotel',]
Airbnb <- Airbnb[Airbnb$room_type == 'Entire home/apt' &
Airbnb$availability_365=='365',]
# make a function for the join
# functions are covered in practical 7
# but see if you can work out what is going on
# hint all you have to do is replace data1 and data2
# with the data you want to use
Joinfun <- function(data1, data2) {
# join OSM and London boroughs
joined <- st_join(data1, data2, join = st_within)
# count the number of hotels per borough
countno <- as.data.frame(count(joined$GSS_CODE))
# join the count back to the borough layer
counted <-left_join(data2, countno, by=c("GSS_CODE"="x"))
return(counted)
}
# use the function for hotels
Hotels <- Joinfun(OSM, Londonborough)
# then for airbnb
Airbnb <- Joinfun(Airbnb, Londonborough)
# now try to arrange the plots with tmap
breaks = c(0, 5, 12, 26, 57, 286)
#change the column name from freq for the legend
colnames(Hotels)[colnames(Hotels)=="freq"] <- "Accom count"
#join data
ti<-st_join(Airbnb, Hotels, join=st_equals)
ti<-st_transform(ti,crs = 4326)
# change the names to match those in later selection
names(ti)[names(ti) == "freq"] <- "Airbnb"
names(ti)[names(ti) == "Accom count"] <- "Hotel"
# combine all the data (accomodation count) so we
# can make an appropraite colour range
accomall<-c(ti$`Hotel`,ti$Airbnb)
```
Now we are going to take our data to make an interative map with drop down selection boxes and a 'slider'. We want to be able to:
(a) select either Hotel or Airbnb data to map
(b) be able to select a colour scheme
(c) filter the boroughs shown using a slider
(d) select what kind of intervals we can use to style the data
(e) have a legend that automatically updates based on the selections (e.g. slider, colour scheme and interval style)
There are plenty of options available in Shiny to make cool interactive features, for more information check out:
* https://shiny.rstudio.com/tutorial/written-tutorial/lesson1/
* https://rstudio.github.io/leaflet/shiny.html
30. Load the packages we'll need here and do some final data manipulation. Just add this right below the code above, i seperate it using a line of ##########################
```{r prac8_shiny2, eval=FALSE, cache=FALSE}
################################################## final data manipulation
library(shiny)
library(leaflet)
library(RColorBrewer)
# we will use this for our dropdown
choice=c("Hotel", "Airbnb")
# remove any NAs from our data and replace with 0
#as a function later on doesn't play ball with them
ti$Hotel[is.na(ti$Hotel)] <- 0
ti$Airbnb[is.na(ti$Airbnb)] <- 0
```
#### User interface
31. Ok, first let's set up the user interface or ```ui```. I've commented the code to descrbie what each bit does.
```{r prac8_shinyUI, eval=FALSE, cache=FALSE}
################################################## ui
# we'll use bootstrappage - a UI definition that can be passed to Shiny
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
# we're using leaflet and have title the outputID map
# this will call it from our server function below
leafletOutput("map", width = "100%", height = "100%"),
# this sets our input panel placement
absolutePanel(top = 10, right = 10,
#
#our ID will be called later to make it interactive
selectInput(inputId = "Accom",
# label the drop down
label = "Accom type",
# what choices will there be
# this uses our choices list from
# earlier
choices = choice,
# Here False means you can only select
# one option
multiple = FALSE
),
#gimme some colour options from colourbrewer
# here the inoutID is colourbrewerpalette
# the lavel is Color Scheme
# rownames provides our choices
selectInput("colourbrewerpalette", "Color Scheme",