::p_load(sf, tmap, sfdep, tidyverse) pacman
In Class Ex 6: Spatial Weights
Setup
Install and load R packages
Importing data
Aspatial data | Attribute table
As tibblr
<- read_csv("data/aspatial/Hunan_2012.csv") hunan2012
Geospatial data
st_read( )
is an sf function. Import Hunan shapefile into R as an sf dataframe.
<- st_read(dsn = "data/geospatial",
hunan layer = "Hunan")
Reading layer `Hunan' from data source
`C:\zoe-chia\IS415\In-class_Ex\In-class_Ex06\data\geospatial'
using driver `ESRI Shapefile'
Simple feature collection with 88 features and 7 fields
Geometry type: POLYGON
Dimension: XY
Bounding box: xmin: 108.7831 ymin: 24.6342 xmax: 114.2544 ymax: 30.12812
Geodetic CRS: WGS 84
Data cleaning
Combine both dataframes with left join
One is tibblr, one is sf, which has a geometric column. The left data frame should be the sf dataframe with geometric data.
We use the left_join function of dplyr. The function automatically joins by the common column, “County”.
<- left_join(hunan, hunan2012) %>%
hunan_GDPPC select(1:4, 7, 15)
Exploratory Data Analysis
Plotting Choropleth Map
tmap_mode('plot')
tm_shape(hunan_GDPPC) +
tm_fill("GDPPC",
style = "quantile",
palette = "Blues",
title = "GDPPC") +
tm_layout(main.title = "Distribution of GDP per capita by district, Hunan Province",
main.title.position = "center",
main.title.size = 0.8,
legend.height = 0.30,
legend.width = 0.25,
frame = TRUE)+
tm_borders(lwd = 0.1,
alpha = 0.6) +
tm_compass(type="8star", size = 2) +
tm_scale_bar() +
tm_grid(alpha = 0.2)
Identify Area (Polygon) Neighbours
Contiguity neighbours method
Queen’s Method
For sf format,
st_contiguity()
is used to derive a contiguity neighbour list by using Queen’s Method. Default isqueen = TRUE
.For sp format, use spdep’s
poly2nb()
(polygon to neighbour) function.dplyr’s
mutate()
creates a new fieldnb
to store the result ofst_contiguity
.before = 1
places the new field as the first column
<- hunan_GDPPC %>%
cn_queen mutate(nb = st_contiguity(geometry),
.before = 1)
Rook’s Method
<- hunan_GDPPC %>%
cn_rook mutate(nb=st_contiguity(geometry, queen = FALSE),
.before = 1)
We now know it’s neighbours.
K-Nearest Neighbours
Computing contiguity weights
Distance based method
Contiguity weights: Queen’s Method
<- hunan_GDPPC %>%
wm_q mutate(nb = st_contiguity(geometry),
wt = st_weights(nb),
.before = 1)
Contiguity weights: Rook’s Method
<- hunan_GDPPC %>%
wm_r mutate(nb = st_contiguity(geometry, queen = FALSE),
wt = st_weights(nb),
.before = 1)
st_dist_band()
lower limit always has to be 0