pacman::p_load(sf, sfdep, tmap, tidyverse, knitr)In-class Exercise 2
Getting Started
Installing and Loading R Packages
Loading R packages
The Data
For this In-class Exercise, the Hunan data sets will be used. They are:
- hunan: a geographical data set in ESRI shapefile format
- Hunan_2012: an attribute data set in csv format
Importing geospatial data
st_read() can be used to read the shape file data set into an R sf dataframe
hunan <- st_read(dsn = 'data/geospatial',
layer = 'Hunan')Reading layer `Hunan' from data source
`D:\phlong2023\ISSS624\In-Class_Ex\In-Class_Ex2\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
Importing attribute table
read_csv() can be used to read the attribute file into an R data frame
hunan_2012 <- read_csv('data/aspatial/Hunan_2012.csv')Combining the two data sets
left_join() can be used to combine the two data sets
Note
In order to retain the geospatial properties, the left data frame must be sf data.frame, in this case it is hunan
hunan_GDPPC <- left_join(hunan, hunan_2012,
by = 'County')%>%
select(1:4, 7, 15) #Retaining the city's name, ID, county name, county type, GDPPC, and geometryDeriving Contiguity Weights: Queen’s Model
The sfdep method entails the creation of a tibble data frame which contains the original data as well as the neighbors list and weights for each polygon , as opposed to creating the contiguity and weight separately in spdep.
wm_q <- hunan_GDPPC %>%
mutate(nb = st_contiguity(geometry), # Default is Queen
wt = st_weights(nb,
style='W'),
.before = 1)Computing Global Moran’s I (old spdep method)
moranI <- global_moran(wm_q$GDPPC,
wm_q$nb,
wm_q$wt)
moranI$I
[1] 0.30075
$K
[1] 7.640659
Computing Local Moran’s I (with sfdep method)
lisa <- wm_q %>%
mutate(local_moran = local_moran(GDPPC, nb, wt, nsim = 99),
.before = 1) %>%
unnest(local_moran)