::p_load(sf, sfdep, tmap, tidyverse, knitr) pacman
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
<- st_read(dsn = 'data/geospatial',
hunan 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
<- read_csv('data/aspatial/Hunan_2012.csv') hunan_2012
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
<- left_join(hunan, hunan_2012,
hunan_GDPPC by = 'County')%>%
select(1:4, 7, 15) #Retaining the city's name, ID, county name, county type, GDPPC, and geometry
Deriving 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.
<- hunan_GDPPC %>%
wm_q mutate(nb = st_contiguity(geometry), # Default is Queen
wt = st_weights(nb,
style='W'),
.before = 1)
Computing Global Moran’s I (old spdep method)
<- global_moran(wm_q$GDPPC,
moranI $nb,
wm_q$wt)
wm_q
moranI
$I
[1] 0.30075
$K
[1] 7.640659
Computing Local Moran’s I (with sfdep method)
<- wm_q %>%
lisa mutate(local_moran = local_moran(GDPPC, nb, wt, nsim = 99),
.before = 1) %>%
unnest(local_moran)