#Package Dependencies/ Data
N.B. There are codeblocks here which have been hidden by default as they are just repeats of the start of ['code'.](Code.html) 
This just the point where in a new environment you would need to load up the same packages as before, and import/create the data in 'code', to make the below graphics produceable in R.
Anything new starts after ///.

If you'd like to see this code, it's visible in the .rmd at ['Map5_Code.Rmd'.](Map5_Code.Rmd). Or directly from github https://github.com/fergustaylor/Arran (in /docs).

```{r include=FALSE}
##Load Packages
#First I need to load up the packages I'll need
library(sf)
library(ggplot2) #development version!
## devtools::install_github("tidyverse/ggplot2")
library(tidyverse)
library(readr)
library(cowplot)
library(sp)
library(gridExtra)
library(dplyr)
library(ggrepel)
library(plyr)
```

```{r include=FALSE}
##Import Postcode Data
#Now I import my data. I filter for the Arran postcodes, (since Arran all begins 'KA27').
#Add download commands for data.
## Finding the Arran coordinates
arrancoordinates <- read.csv("../alldata/ukpostcodes.csv") %>%
 filter(substr(postcode,1,4)=="KA27")

#Find way to replace with existing SIMD shape files
arransubsect <- read_sf("../alldata/Scotland_pcs_2011") %>%
filter(substr(label,1,4)=="KA27")
```

```{r include=FALSE}
##Import SIMD data
#Now I load the SIMD data, containing the geometries (shapefiles) and SIMD data (percentiles, etc)
reorderedvector<- c("S01011174", "S01011171", "S01011177", "S01011176", "S01011175", "S01011173", "S01011172" )

arran2016 <- read_sf("../alldata/SG_SIMD_2016")[c(4672,4666,4669,4671,4667,4668,4670),] %>%
  slice(match(reorderedvector, DataZone))

Arrandz2012 <- c(4409,4372,4353,4352,4351,4350,4349)

arran2012 <- read_sf("../alldata/SG_SIMD_2012")[Arrandz2012,]
arran2009 <- read_sf("../alldata/SG_SIMD_2009")[Arrandz2012,]
arran2006 <- read_sf("../alldata/SG_SIMD_2006")[Arrandz2012,]
arran2004 <- read_sf("../alldata/SG_SIMD_2004")[Arrandz2012,]

sharedvariables <- intersect(colnames(arran2016), colnames(arran2012)) %>%
  intersect(colnames(arran2009))  %>%
  intersect(colnames(arran2006))  %>%
  intersect(colnames(arran2004))
  
arran20162 <- arran2016 %>%
  select(sharedvariables) %>%
  mutate(year="2016")
arran20122 <- arran2012 %>%
  select(sharedvariables) %>%
  mutate(year="2012")
arran20092 <- arran2009 %>%
  select(sharedvariables) %>%
  mutate(year="2009")
arran20062 <- arran2006 %>%
  select(sharedvariables) %>%
  mutate(year="2006")
arran20042 <- arran2004 %>%
  select(sharedvariables) %>%
  mutate(year="2004")

arransimd <- rbind(arran20162,arran20122,arran20092,arran20062,arran20042) %>%
mutate(
    lon = map_dbl(geometry, ~st_centroid(.x)[[1]]),
    lat = map_dbl(geometry, ~st_centroid(.x)[[2]])
    )

arransimd$listID <- revalue(arransimd$DataZone,
               c("S01004409"="S01004409/S01011174", "S01004372"="S01004372/S01011171", "S01004353"="S01004353/S01011177", "S01004352"="S01004352/S01011176", "S01004351"="S01004351/S01011175", "S01004350"="S01004350/S01011173", "S01004349"="S01004349/S01011172", "S01011174"="S01004409/S01011174", "S01011171"="S01004372/S01011171", "S01011177"="S01004353/S01011177", "S01011176"="S01004352/S01011176", "S01011175"="S01004351/S01011175", "S01011173"="S01004350/S01011173", "S01011172"="S01004349/S01011172"))
```

```{r include=FALSE}
#Now I want to overlay the postcodes by Datazone.
#To do this I've converted both the Arran coordinates and Arran (2016) shapefiles into spatial points/polygons, converted them into a common CRS, and then compared them by using 'plyr::over()'.
#This gives me the object 'namingdzpostcode', with the postcode rows grouped into IDs (unidentified datazones).

simple.sf <- st_as_sf(arrancoordinates, coords=c('longitude','latitude'))
st_crs(simple.sf) <- 4326

exampleshapes <- sf:::as_Spatial(arran2016$geometry) %>%
  spTransform(CRS("+proj=longlat +datum=WGS84"))

examplepoints <- sf:::as_Spatial(simple.sf$geom) %>%
  spTransform(CRS("+proj=longlat +datum=WGS84"))

namingdzpostcode <- over(exampleshapes, examplepoints, returnList = TRUE)
```

```{r include=FALSE}
#I can then take a member reference from the orginal postcode list, which gives me a selection of the rows in that DZ. For simplicity I've written this as a new function. 
##Mutate arrancoordinates to label the IDs
function100 <- function(argument) 
{
  argument <- arrancoordinates[namingdzpostcode[[argument]],] %>% mutate(DataZone=argument)
}

arrancoordinates <- lapply(1:7,function100)
arrancoordinates <- rbind(arrancoordinates[[1]], arrancoordinates[[2]], arrancoordinates[[3]], arrancoordinates[[4]], arrancoordinates[[5]], arrancoordinates[[6]], arrancoordinates[[7]])

arrancoordinates$listID <- revalue(as.character(arrancoordinates$DataZone),
               c('1'="S01004409/S01011174", '2'="S01004372/S01011171", '3'="S01004353/S01011177", '4'="S01004352/S01011176", '5'="S01004351/S01011175", '6'="S01004350/S01011173", '7'="S01004349/S01011172"))
```

```{r include=FALSE}
##Labelling the namingdzpostcode list
names(namingdzpostcode) <- c(unique(arransimd$listID))
```

///

#Mapping
```{r message=FALSE, warning=FALSE}
library(rgdal)
library(leaflet)
library(ggmap)
library(htmlwidgets)
```

#Coordinates
```{r}
postcodelist <- paste(unique(arrancoordinates$listID), "Postcodes", sep=" ")
datazonelist <- paste(unique(arrancoordinates$listID), "Datazones", sep=" ")

m = leaflet() %>% addTiles() %>% setView(-5.227680, 55.582338, zoom = 10) 
```

#Example Markers
Inputing example markers.
```{r message=FALSE, warning=FALSE}
cliniccoordinates <- read.csv("../alldata/clinics.csv") %>%
dplyr::left_join(arrancoordinates, by="postcode")
#change to character
cliniccoordinates$X <- as.character(cliniccoordinates$X)
```

#Map
##Overlaying percentiles
```{r}
exampleshapes2 <- as(arransimd, "Spatial") %>%
spTransform(CRS("+proj=longlat +datum=WGS84"))
```

##Convert to function
```{r}
functionmap <- function(argument, argument2) 
{
pal2 <- colorNumeric(palette = "magma",
  domain = argument)

listlistlist <- paste(datazonelist, argument, sep=" ")

m %>% 

#alldatazones  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2004, ], 
            weight = 2, 
            label = listlistlist[29:35],
            group = "2004",
            fillOpacity =0.8,
            color = ~pal2(argument[29:35]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2004") %>% 
  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2006, ], 
            weight = 2, 
            label = listlistlist[22:28],
            group = "2006",
            fillOpacity =0.8,
            color = ~pal2(argument[22:28]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2006") %>% 
  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2009, ], 
            weight = 2, 
            label = listlistlist[15:21],
            group = "2009",
            fillOpacity =0.8,
            color = ~pal2(argument[15:21]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2009") %>% 
  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2012, ], 
            weight = 2, 
            label = listlistlist[8:14],
            group = "2012",
            fillOpacity =0.8,
            color = ~pal2(argument[8:14]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2012") %>% 

addPolygons(data=exampleshapes2[exampleshapes2$year == 2016, ], 
            weight = 2, 
            label = listlistlist[1:7],
            group = "2016",
            fillOpacity =0.8,
            color = ~pal2(argument[1:7]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2016") %>% 
  
#cliniccoordinates
addMarkers(
    lng = cliniccoordinates$longitude, lat = cliniccoordinates$latitude,
    label = cliniccoordinates$X,
    labelOptions = labelOptions(noHide = F), group = cliniccoordinates$X) %>%
  hideGroup(cliniccoordinates$X) %>%   

addLegend("bottomleft", pal = pal2, values = argument,
    title = argument2,
    opacity = 1
  )  %>%  

#Layers control
addLayersControl(
    baseGroups = c("2004", "2006", "2009", "2012", "2016", "Nothing"),
    overlayGroups = c(cliniccoordinates$X),
    options = layersControlOptions(collapsed = TRUE)
  )
}
```

##Each map
[See these maps.](https://fergustaylor.github.io/Arran/Map5view.html)
```{r}
map51 <- functionmap(exampleshapes2$Rank, "Rank")
saveWidget(map51, file="map51.html")

map54 <- functionmap(exampleshapes2$Vigintile, "Vigintile")
saveWidget(map54, file="map54.html")
map55 <- functionmap(exampleshapes2$Percentile, "Percentile")
saveWidget(map55, file="map55.html")
map56 <- functionmap(exampleshapes2$IncRate, "IncRate")
saveWidget(map56, file="map56.html")
map57 <- functionmap(exampleshapes2$IncRank, "IncRank")
saveWidget(map57, file="map57.html")
map58 <- functionmap(exampleshapes2$EmpRate, "EmpRate")
saveWidget(map58, file="map58.html")
map59 <- functionmap(exampleshapes2$HlthRank, "HlthRank")
saveWidget(map59, file="map59.html")
map510 <- functionmap(exampleshapes2$EduRank, "EduRank")
saveWidget(map510, file="map510.html")
map511 <- functionmap(exampleshapes2$GAccRank, "GAccRank")
saveWidget(map511, file="map511.html")
map512 <- functionmap(exampleshapes2$HouseRank, "HouseRank")
saveWidget(map512, file="map512.html")
```

```{r}
functionmap2 <- function(argument, argument2, argument3) 
{
listlistlist <- paste(datazonelist, argument, sep=" ")

m %>% 

#alldatazones  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2004, ], 
            weight = 2, 
            label = listlistlist[29:35],
            group = "2004",
            fillOpacity =0.8,
            color = ~argument3(argument[29:35]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2004") %>% 
  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2006, ], 
            weight = 2, 
            label = listlistlist[22:28],
            group = "2006",
            fillOpacity =0.8,
            color = ~argument3(argument[22:28]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2006") %>% 
  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2009, ], 
            weight = 2, 
            label = listlistlist[15:21],
            group = "2009",
            fillOpacity =0.8,
            color = ~argument3(argument[15:21]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2009") %>% 
  
addPolygons(data=exampleshapes2[exampleshapes2$year == 2012, ], 
            weight = 2, 
            label = listlistlist[8:14],
            group = "2012",
            fillOpacity =0.8,
            color = ~argument3(argument[8:14]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2012") %>% 

addPolygons(data=exampleshapes2[exampleshapes2$year == 2016, ], 
            weight = 2, 
            label = listlistlist[1:7],
            group = "2016",
            fillOpacity =0.8,
            color = ~argument3(argument[1:7]),
            highlightOptions = highlightOptions(color = "black", weight = 2,
      bringToFront = TRUE)) %>% 
hideGroup("2016") %>% 
  
#cliniccoordinates
addMarkers(
    lng = cliniccoordinates$longitude, lat = cliniccoordinates$latitude,
    label = cliniccoordinates$X,
    labelOptions = labelOptions(noHide = F), group = cliniccoordinates$X) %>%
  hideGroup(cliniccoordinates$X) %>%   

addLegend("bottomleft", pal = argument3, values = argument,
    title = argument2,
    opacity = 1
  )  %>%  

#Layers control
addLayersControl(
    baseGroups = c("2004", "2006", "2009", "2012", "2016", "Nothing"),
    overlayGroups = c(cliniccoordinates$X),
    options = layersControlOptions(collapsed = TRUE)
  )
}
```

```{r}
pal3 <- colorBin(palette = "magma",
  domain = 0:5, bins = 5)

pal4 <- colorBin(palette = "magma",
  domain = 0:10, bins = 10)
```

```{r}
map52 <- functionmap2(exampleshapes2$Quintile, "Quintile", pal3)
saveWidget(map52, file="map52.html")
map53 <- functionmap2(exampleshapes2$Decile, "Decile", pal4)
saveWidget(map53, file="map53.html")
```

[See these maps.](https://fergustaylor.github.io/Arran/Map5view.html)

[Go back.](https://fergustaylor.github.io/Arran)
