# Geocomputation with spatial data
# Attribute Joins!
library(rgdal)
## Loading required package: sp
## rgdal: version: 1.2-18, (SVN revision 718)
##  Geospatial Data Abstraction Library extensions to R successfully loaded
##  Loaded GDAL runtime: GDAL 2.2.3, released 2017/11/20
##  Path to GDAL shared files: C:/Users/Lukas/Documents/R/win-library/3.4/rgdal/gdal
##  GDAL binary built with GEOS: TRUE 
##  Loaded PROJ.4 runtime: Rel. 4.9.3, 15 August 2016, [PJ_VERSION: 493]
##  Path to PROJ.4 shared files: C:/Users/Lukas/Documents/R/win-library/3.4/rgdal/proj
##  Linking to sp version: 1.2-7
lnd <- readOGR("data/london_sport.shp")
## OGR data source with driver: ESRI Shapefile 
## Source: "C:\Users\Lukas\Dropbox\R- Creating Maps\Creating-maps-in-R-master\Creating-maps-in-R-master\data\london_sport.shp", layer: "london_sport"
## with 33 features
## It has 4 fields
## Integer64 fields read as strings:  Pop_2001
plot(lnd)

nrow(lnd)
## [1] 33
# New Join (addition of TCE for 2012 into lnd database)
TCE_data<- read.csv("data/london-borough-profiles-2014.csv",
                    stringsAsFactors = FALSE) # TCE = Total Carbon Emissions
head(TCE_data$Total.carbon.emissions..2012.) # info about tce
## [1] ""        "1,499.0" "780.8"   "1,542.0" "1,096.0" "1,358.2"
# Get rid of commas and convert to numeric
TCE_data$Total.carbon.emissions..2012. <- gsub(",","", TCE_data$Total.carbon.emissions..2012.)
Carbon_Emissions_12 <- as.numeric(TCE_data$Total.carbon.emissions..2012.)

Borough <- as.factor(TCE_data$Area.name)

# Aggregate total carbon emissions to districts
TCE <- aggregate(Carbon_Emissions_12 ~ Borough, FUN = sum, data = TCE_data)
head(TCE, 2)
##                Borough Carbon_Emissions_12
## 1 Barking and Dagenham               780.8
## 2               Barnet              1542.0
# check to see if related variables run true
lnd$name %in% TCE$Borough
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [15] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [29] TRUE TRUE TRUE TRUE TRUE
#load dplyr package
library(dplyr) 
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
head(lnd$name)
## [1] Bromley              Richmond upon Thames Hillingdon          
## [4] Havering             Kingston upon Thames Sutton              
## 33 Levels: Barking and Dagenham Barnet Bexley Brent Bromley ... Westminster
head(TCE$Borough)
## [1] Barking and Dagenham Barnet               Bexley              
## [4] Brent                Bromley              Camden              
## 39 Levels:  Barking and Dagenham Barnet Bexley Brent Bromley ... Westminster
# join data and print map
lnd@data <- left_join(lnd@data, TCE, by = c('name'= 'Borough'))
## Warning: Column `name`/`Borough` joining factors with different levels,
## coercing to character vector
library(tmap)
qtm(lnd, "Carbon_Emissions_12")

tmap_mode("view")
## tmap mode set to interactive viewing
# tmap section
# install the CRAN version of tmap
library(tmap)
vignette("tmap-nutshell")
## starting httpd help server ...
##  done
qtm(shp = lnd, fill = "Carbon_Emissions_12", fill.palette = "Blues")
# Create a series of maps using tm_facets command
tm_shape(lnd) +
  tm_fill("Carbon_Emissions_12", thres.poly = 0) +
  tm_facets("name", free.coords = TRUE, drop.units = TRUE)
## Warning in limit_nx(nxa): The number of facets exceeds the limit of 4. The limit can be extended to 33 with:
## tmap_options(tmap.limits=c(facets.plot=64, facets.view=33))
# create tmap (leaflet) of london with color segmentation by carbon emissions levels (2012)
lnd_wgs = spTransform(lnd, CRS("+init=epsg:4326")) # convert to london CRS
if(curl::has_internet()) {
  osm_tiles = tmaptools::read_osm(bbox(lnd_wgs)) # download images from OSM
  tm_shape(osm_tiles) + tm_raster() +
    tm_shape(lnd_wgs) +
    tm_fill("Carbon_Emissions_12", fill.title = "Total Carbon Emissions, 2012", scale = 0.8, alpha = 0.5) +
    tm_layout(legend.position = c(1, 0.08)) 
} else {
  tm_shape(lnd_wgs) +
    tm_fill("Carbon_Emissions_12", fill.title = "Total Carbon Emissions, 2012", scale = 0.8, alpha = 0.5) +
    tm_layout(legend.position = c(1, 0.08))
}
## Warning: Current projection unknown. Long lat coordinates (wgs84) assumed.
## Raster data contains OpenStreetMapData (read with read_osm). Therefore, the basemap has been set to "OpenStreetMap.Mapnik"
tmap_mode("view")
## tmap mode set to interactive viewing
# New Join 2 (addition of TCE for 2014 into lnd database)
TCE_data_1<- read.csv("data/london-borough-profiles2014.csv",
                    stringsAsFactors = FALSE) # TCE = Total Carbon Emissions
head(TCE_data_1$Total_carbon_emissions_.2014.) # info about tce
## [1] "1036" "644"  "1415" "975"  "1175" "1180"
# Convert to numeric
Carbon_Emissions_14<- as.numeric(TCE_data_1$Total_carbon_emissions_.2014.)
## Warning: NAs introduced by coercion
Borough_14 <- as.factor(TCE_data_1$Area_name)

# Aggregate total carbon emissions to districts
TCE_1 <- aggregate(Carbon_Emissions_14 ~ Borough_14, FUN = sum, data = TCE_data_1)
head(TCE_1, 2)
##             Borough_14 Carbon_Emissions_14
## 1 Barking and Dagenham                 644
## 2               Barnet                1415
# check to see if related variables run true
lnd$name %in% TCE_1$Borough_14
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [15] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [29] TRUE TRUE TRUE TRUE TRUE
TCE$Borough %in% TCE_1$Borough_14
##  [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
## [12]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
## [23]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE
## [34]  TRUE  TRUE  TRUE  TRUE  TRUE
# Delete rows which do not match
TCE <- TCE[-c(20, 29), ]

#load dplyr package
library(dplyr) 

head(lnd$name)
## [1] "Bromley"              "Richmond upon Thames" "Hillingdon"          
## [4] "Havering"             "Kingston upon Thames" "Sutton"
head(TCE_1$Borough_14)
## [1] Barking and Dagenham Barnet               Bexley              
## [4] Brent                Bromley              Camden              
## 38 Levels: Barking and Dagenham Barnet Bexley Brent Bromley ... Westminster
# join data and print map
lnd@data <- left_join(lnd@data, TCE_1, by = c('name'= 'Borough_14'))
## Warning: Column `name`/`Borough_14` joining character vector and factor,
## coercing into character vector
library(tmap)
qtm(lnd, "Carbon_Emissions_14")
tmap_mode("view")
## tmap mode set to interactive viewing
# combine data from TCE_1 to TCE
TCE <- cbind(TCE, TCE_1$Carbon_Emissions_14)
colnames(TCE) <- c("Borough", "TCE_12", "TCE_14")

# tmap
# install the CRAN version of tmap
library(tmap)
vignette("tmap-nutshell")
qtm(shp = lnd, fill = "Carbon_Emissions_14", fill.palette = "Blues")
# Create a series of maps using tm_facets command
tm_shape(lnd) +
  tm_fill("Carbon_Emissions_14", thres.poly = 0) +
  tm_facets("name", free.coords = TRUE, drop.units = TRUE)
## Warning in limit_nx(nxa): The number of facets exceeds the limit of 4. The limit can be extended to 33 with:
## tmap_options(tmap.limits=c(facets.plot=64, facets.view=33))
# create tmap (leaflet) of london with color segmentation by carbon emissions levels (2014)
lnd_wgs = spTransform(lnd, CRS("+init=epsg:4326")) # convert to london CRS
if(curl::has_internet()) {
  osm_tiles = tmaptools::read_osm(bbox(lnd_wgs)) # download images from OSM
  tm_shape(osm_tiles) + tm_raster(palette = "Blues") +
    tm_shape(lnd_wgs) +
    tm_fill("Carbon_Emissions_14", fill.title = "Total Carbon Emissions, 2014", scale = 0.8, alpha = 0.5) +
    tm_layout(legend.position = c(1, 0.08)) 
} else {
  tm_shape(lnd_wgs) +
    tm_fill("Carbon_Emissions_14", fill.title = "Total Carbon Emissions, 2014", scale = 0.8, alpha = 0.5) +
    tm_layout(legend.position = c(1, 0.08))
}
## Warning: Current projection unknown. Long lat coordinates (wgs84) assumed.
## Raster data contains OpenStreetMapData (read with read_osm). Therefore, the basemap has been set to "OpenStreetMap.Mapnik"
tmap_mode("view")
## tmap mode set to interactive viewing
# 終わり