Inferential Spatial Statistics and for Continuous Outcomes
2025-09-22
Spatial data come in different forms, and the methods of analysis depend on the type.
1. Areal Data
- Definition: Data aggregated over spatial units (e.g., districts, census tracts).
- Examples: HIV prevalence by district, unemployment rates by municipality.
- Key feature: Exact individual locations are not known — only summaries over polygons.
- Typical models: Conditional Autoregressive (CAR) models, Besag–York–Mollié (BYM) models.
\[ Y_i \sim f(\mu_i), \quad \mu_i \text{ depends on spatial structure across areas} \]
2. Geostatistical Data
- Definition: Data observed at a set of irregularly spaced locations in continuous space.
- Examples: Rainfall at weather stations, soil nutrients at sampled sites.
- Key feature: Each observation has a coordinate; spatial correlation is modeled explicitly.
- Typical models: Gaussian random fields, kriging.
\[ Z(s) = \mu(s) + \varepsilon(s), \quad \text{with } \text{Cov}(Z(s), Z(s')) = C(s-s') \]
3. Point Pattern Data
- Definition: The locations of events themselves are the data.
- Examples: Crime incident locations, tree positions in a forest, disease cases in a region.
- Key feature: The focus is on clustering, randomness, or inhibition of events.
- Typical models: Poisson point processes, Ripley’s \(K\) function, pair correlation.
\[ \lambda(s) = \lim_{|ds|\to 0} \frac{E[N(ds)]}{|ds|} \]
Summary Table
| Feature | Areal Data | Geostatistical Data | Point Pattern Data |
|---|---|---|---|
| Units of observation | Polygons (areas) | Specific sample points | Event locations themselves |
| Examples | HIV prevalence by district | Rainfall at stations | Crime incident locations |
| Main question | Differences between regions? | Predict at unmeasured sites? | Are events clustered or random? |
| Methods | CAR/BYM models | Kriging, Gaussian processes | Point process models |
Schematic Illustration
Geographic data can be represented using a data storage format called a shapefile, which stores the location, shape, and attributes of geographic features such as points, lines, and polygons.
A shapefile is not a single file, but rather a collection of related files that share the same base name and are stored in the same directory.
Mandatory files
A shapefile has three mandatory components:
.shp: contains the geometry data.
.shx: positional index of the geometry data, allowing navigation of the.shpfile.
.dbf: stores the attribute data for each shape.
Optional files
Additional files can also be part of a shapefile, providing further information:
.prj: plain text file describing the projection.
.sbnand.sbx: spatial index of the geometry data.
.shp.xml: geospatial metadata in XML format.
Plotting Spatial Data in R
Load packages
library(sf)
library(tmap)
library(leaflet)
library(spdep)
library(stringdist)
library(sf)
library(SpatialEpi)
library(raster)
library(tidyverse)
library(dplyr)
library(spData)
library(sf)
library(mapview)Read in the map files
- To read a shapefile, we use the
st_read()function from the sf package.
first_map <- st_read("sdavr_camden/shapefiles/Camden_oa11.shp")
## Reading layer `Camden_oa11' from data source
## `C:\Users\r1953\OneDrive\Desktop\frequentist\blog\Spatial\sdavr_camden\shapefiles\Camden_oa11.shp'
## using driver `ESRI Shapefile'
## Simple feature collection with 749 features and 1 field
## Geometry type: POLYGON
## Dimension: XY
## Bounding box: xmin: 523954.5 ymin: 180959.8 xmax: 531554.9 ymax: 187603.6
## Projected CRS: Transverse_MercatorQuick check
# quick check
print(first_map)
## Simple feature collection with 749 features and 1 field
## Geometry type: POLYGON
## Dimension: XY
## Bounding box: xmin: 523954.5 ymin: 180959.8 xmax: 531554.9 ymax: 187603.6
## Projected CRS: Transverse_Mercator
## First 10 features:
## OA11CD geometry
## 1 E00004527 POLYGON ((530648.4 181230.2...
## 2 E00004525 POLYGON ((530511.3 181531.2...
## 3 E00004522 POLYGON ((530207 181434, 53...
## 4 E00004287 POLYGON ((524355.4 185053.6...
## 5 E00004206 POLYGON ((528718.5 184565, ...
## 6 E00004200 POLYGON ((529332.4 181816.6...
## 7 E00004281 POLYGON ((529826 184537, 52...
## 8 E00004464 POLYGON ((528360.6 184593.5...
## 9 E00004460 POLYGON ((527934 184846.9, ...
## 10 E00004461 POLYGON ((528045.9 184601.4...class(first_map)
## [1] "sf" "data.frame"Load the main dataset for this exercise.
dat_cens <-read_csv("sdavr_practicaldata.csv")head(dat_cens)| OA | White_British | Low_Occupancy | Unemployed | Qualification |
|---|---|---|---|---|
| E00004120 | 42.35669 | 6.2937063 | 1.893939 | 73.62637 |
| E00004121 | 47.20000 | 5.9322034 | 2.688172 | 69.90291 |
| E00004122 | 40.67797 | 2.9126214 | 1.212121 | 67.58242 |
| E00004123 | 49.66216 | 0.9259259 | 2.803738 | 60.77586 |
| E00004124 | 51.13636 | 2.0000000 | 3.816794 | 65.98639 |
| E00004125 | 41.41791 | 3.9325843 | 3.846154 | 74.20635 |
joins data to the shapefile
census_data <- merge(first_map, dat_cens, by.x="OA11CD", by.y="OA")Creating a simple map
- we load in the shapefile with the
tm_shape()function then add in thetm_fill()function which is where we can decide how the polygons are filled in.
Change pallette
Setting the Colour Intervals
We have a range of different interval options in the style parameter.
Each of them will greatly impact how your data is visualised.
To do this, you enter style = followed by one of the options below:
- equal – divides the range of the variable into n equal parts.
- pretty – chooses a number of breaks to fit a sequence of equally spaced, “round” values.
This makes the intervals tidy and easy to remember.
- quantile – ensures an equal number of cases in each group.
- jenks – looks for natural breaks in the data.
- cat – used if the variable is categorical (i.e., not continuous).
We can also change the number of intervals in the colour scheme and how the intervals are spaced.
Changing the number of intervals is straightforward: just set n = n (note that the default interval setting may still round the number).
For example, here we use 7 shades instead of the default 5.
Adding Borders
You can edit the borders of the shapefile with the tm_borders() function, which has many arguments.
For example, alpha denotes the level of transparency on a scale from 0 to 1,
where 0 is completely transparent and 1 is fully opaque.
# Add borders with transparency
tm_shape(census_data) +
tm_fill("Qualification", palette = "Reds") +
tm_borders(alpha = 0.4)Adding a north arrow
- We can also enter a north arrow with tm_compass.
tm_shape(census_data)+
tm_fill("Qualification",
palette="Reds",
style="quantile",
title="%withaQualification") +
tm_borders(alpha=.4)+
tm_compass()+
tm_layout(title="Camden,London",
legend.text.size=1.1,
legend.title.size=1.4,
legend.position= c("right","top"),
frame=FALSE)- when working with point data, the spatial relationships among events (their proximity) are more or less unambiguously given by their relative location, or more precisely by their distance. Hence, we have
- quadrat-based techniques (relative location with respect to a grid),
- kernel density (relative location with respect to the center of a kernel function), and
- distance-based techniques (event-to-event and point-to-event distances).
In the case of area data, spatial proximity can be represented in more ways, given the characteristics of areas. In particular, an area contains an infinite number of points, and measuring distance between two areas leads to an infinite number of results, depending on which pairs of points within two zones are used to measure the distance.
Consider Figure below . Which of zones \(A_2\), \(A_3\), and \(A_4\) is closer (or more proximate) to \(A_1\)?
- if points are selected in such a way that they are on the overlapping edges of two contiguous areas, the distance between these two areas clearly is zero, and they must be proximate.
Spatial Weights Matrices
A spatial weights matrix is an arrangement of values (or weights) for all pairs of zones in a system. For instance, in a zoning system such as shown in Figure 1, with 6 zones, there will be \(6 \times 6\) such weights. The weights are organized by rows, in such a way that each zone has a corresponding row of weights. For example, zone \(A_1\) in Figure 1 has the following weights, one for each zone in the system: \[ w_{1\cdot} = [w_{11}, w_{12}, w_{13}, w_{14}, w_{15}, w_{16}] \]
The values of the weights depend on the adjacency criterion adopted. The simplest coding scheme is when we assign a value of 1 to pairs of zones that are adjacent, and a value of 0 to pairs of zones that are not.
Lets formalize the two criteria mentioned above:
- Rook criterion
\[ w_{ij}=\bigg\{\begin{array}{l l} 1\text{ if } A_i \text{ and } A_j \text{ share an edge}\\ 0\text{ otherwise}\\ \end{array} \] If rook adjacency is used, the weights for zone \(A_6\) are as follows: \[ w_{6\cdot} = [0, 0, 0, 1, 1, 0]. \]
As you can see, the adjacent areas from the perspective of \(A_6\) are \(A_4\) and \(A_5\) by virtue of sharing an edge. These two areas receive weights of 1. On the other hand, \(A_1\), \(a_2\), and \(A_3\) are not adjacent, and therefore receive a weight of zero. Notice how the weight \(w_{66}\) is set to zero. By convention, an area is not its own neighbor!
- Queen criterion
\[ w_{ij}=\bigg\{\begin{array}{l l} 1\text{ if } A_i \text{ and } A_j \text{ share an edge or a vertex}\\ 0\text{ otherwise}\\ \end{array} \]
If queen adjacency is used, the weights for zone \(A_6\) are as follows: \[ w_{6\cdot} = [0, 1, 0, 1, 1, 0]. \]
As you can see, the adjacent areas from the perspective of \(A_6\) are \(A_4\) and \(A_5\) (by virtue of sharing an edge), and \(A_2\) (by virtue of sharing a vertex). These three areas receive weights of 1. On the other hand, \(A_1\) and \(A_3\) are not adjacent, and therefore receive a weight of zero. Again, weight \(w_{66}\) is set to zero.
The set of weights above define the neighborhood of \(A_6\).
The spatial weights matrix for the whole system in Figure 1 is as follows: \[ \textbf{W}=\left (\begin{array}{c c c c c c} 0 & 1 & 1 & 1 & 0 & 0\\ 1 & 0 & 0 & 1 & 1 & 1\\ 1 & 0 & 0 & 1 & 0 & 0\\ 1 & 1 & 1 & 0 & 1 & 1\\ 0 & 1 & 0 & 1 & 0 & 1\\ 0 & 1 & 0 & 1 & 1 & 0\\ \end{array} \right). \]
Compare the matrix to the zoning system. The spatial weights matrix has the following properties:
The main diagonal elements of the matrix are all zeros (no area is its own neighbor).
Each zone has a row of weights in the matrix: row number one corresponds to \(A_1\), row number two corresponds to \(A_2\), and so on.
Likewise, each zone has a column of weights.
The sum of all values in a row gives the total number of neighbors for a zone. That is: \[ \text{The total number of neighbors of } A_i \text{ is given by: }\sum_{j=1}^{n}{w_{ij}} \]
The spatial weights matrix is often processed to obtain a row-standardized spatial weights matrix. This procedure consists of dividing every weight by the sum of its corresponding row (i.e., by the total number of neighbors of the zone), as follows: \[ w_{ij}^{st}=\frac{w_{ij}}{\sum_{j=1}^n{w_{ij}}} \]
The row-standardized weights matrix for the system in Figure 1 is: \[ \textbf{W}^{st}=\left (\begin{array}{c c c c c c} 0 & 1/3 & 1/3 & 1/3 & 0 & 0\\ 1/4 & 0 & 0 & 1/4 & 1/4 & 1/4\\ 1/2 & 0 & 0 & 1/2 & 0 & 0\\ 1/5 & 1/5 & 1/5 & 0 & 1/5 & 1/5\\ 0 & 1/3 & 0 & 1/3 & 0 & 1/3\\ 0 & 1/3 & 0 & 1/3 & 1/3 & 0\\ \end{array} \right). \]
The row-standardized spatial weights matrix has the following properties:
Each weight now represents the proportion of a neighbor out of the total of neighbors. For instance, since the total of neighbors of \(A_1\) is 3, each neighbor contributes 1/3 to that total.
The sum of all weights over a row equals 1, or 100% of all neighbors for that zone.
Creating Spatial Weights Matrices in R
Coding spatial weights matrices by hand is a tedious and error-prone process. Fortunately, functions to generate them exist in R. The package spdep in particular has a number of useful utilities for working with spatial weights matrices.
Using Map of South Africa focusing on Provinces
p <- st_read("ZAF_adm/ZAF_adm1_1.shp", quiet = TRUE)
p$percent <- c(21.9, 24.6, 15.5, 15.5, 13.4, 16.2, 21.2, 25.5, 28.9)
mapview(p, zcol = "percent")p |>
as.data.frame()| ID_0 | ISO | NAME_0 | ID_1 | NAME_1 | TYPE_1 | ENGTYPE_1 | NL_NAME_1 | VARNAME_1 | geometry | percent |
|---|---|---|---|---|---|---|---|---|---|---|
| 211 | ZAF | South Africa | 1 | Eastern Cape | Provinsie | Province | NA | Oos-Kaap | MULTIPOLYGON (((25.64375 -3… | 21.9 |
| 211 | ZAF | South Africa | 2 | Free State | Provinsie | Province | NA | Orange Free State|Vrystaat | MULTIPOLYGON (((27.98611 -2… | 24.6 |
| 211 | ZAF | South Africa | 3 | Gauteng | Provinsie | Province | NA | Pretoria/Witwatersrand/Vaal | MULTIPOLYGON (((28.75139 -2… | 15.5 |
| 211 | ZAF | South Africa | 4 | KwaZulu-Natal | Provinsie | Province | NA | Natal and Zululand | MULTIPOLYGON (((31.63736 -2… | 15.5 |
| 211 | ZAF | South Africa | 5 | Limpopo | Provinsie | Province | NA | Noordelike Provinsie|Northern Transvaal|Northern Province | MULTIPOLYGON (((29.66671 -2… | 13.4 |
| 211 | ZAF | South Africa | 6 | Mpumalanga | Provinsie | Province | NA | Eastern Transvaal | MULTIPOLYGON (((31.87835 -2… | 16.2 |
| 211 | ZAF | South Africa | 7 | North West | Provinsie | Province | NA | North-West|Noordwes | MULTIPOLYGON (((26.40328 -2… | 21.2 |
| 211 | ZAF | South Africa | 8 | Northern Cape | Provinsie | Province | NA | Noord-Kaap | MULTIPOLYGON (((16.99514 -2… | 25.5 |
| 211 | ZAF | South Africa | 9 | Western Cape | Provinsie | Province | NA | Wes-Kaap | MULTIPOLYGON (((19.66764 -3… | 28.9 |
The first step to create a spatial weights matrix is to find the neighbors (i.e., areas adjacent to) for each area. The function poly2nb is used for this (note that the default adjacency criterion is queen):
w <- poly2nb(p, row.names=p$PR_CODE,queen = T)The value (output) of the function is an object of class nb:
class(w)
## [1] "nb"- The function
summary()applied to an object of this class gives some useful information about the neighbors in the region, including the number of zones in this system (\(9\)), the total number of neighbors (\(34\)), and the percentage of neighbors out of all pairs of areas (41.98%; conversely, (1-41.98%) of all possible zone pairs are not neighbors!) :
summary(w)
## Neighbour list object:
## Number of regions: 9
## Number of nonzero links: 34
## Percentage nonzero weights: 41.97531
## Average number of links: 3.777778
## Link number distribution:
##
## 2 3 4 6
## 1 2 5 1
## 1 least connected region:
## 9 with 2 links
## 1 most connected region:
## 2 with 6 linksA closer look
p <- st_as_sf(p)
library(tmap)
tm_shape(p) +
tm_polygons()+
tm_fill("percent", style = "quantile", n=5, palette = "Reds", title = "Hypertension prevalence") +
tm_borders(alpha = .4)+
tm_compass() +
tm_text("NAME_1") +
tm_layout(title = "South AFRICA, DHIS2016",
legend.text.size = 0.5,
legend.title.size =0.5 ,
legend.position = c("right", "bottom"),
frame = FALSE)The nb object is a list that contains the neighbors for each zone. For instance, the neighbors of province Eastern Cape (the first tract in the dataframe) are the following Provinces:
p$NAME_1[w[[1]]]
## [1] "Free State" "KwaZulu-Natal" "Northern Cape" "Western Cape"- Based on the Queen Contiquity , we can see that indeed eastern cape is closer to “Free State” , “KwaZulu-Natal” ,“Northern Cape” and “Western Cape” (by virtue of sharing an edge)
The list of neighbors can be converted into a list of entries in a spatial weights matrix \(W\) by means of the function nb2listw (for “neighbors to matrix W in list form”):
B is the basic binary coding, W is row standardised (sums over all links to n), C is globally standardised (sums over all links to n), U is equal to C divided by the number of neighbours (sums over all links to unity), while S is the variance-stabilizing coding scheme proposed by Tiefelsdorf et al.
p.w <- nb2listw(w, style='W')
p.w
## Characteristics of weights list object:
## Neighbour list object:
## Number of regions: 9
## Number of nonzero links: 34
## Percentage nonzero weights: 41.97531
## Average number of links: 3.777778
##
## Weights style: W
## Weights constants summary:
## n nn S0 S1 S2
## W 9 81 9 4.944444 36.86111- We can use base
Rfunctions to visualize the neighbors (adjacent) areas in our system:
A closer look
#display.brewer.all()
p <- st_as_sf(p)
library(tmap)
tm_shape(p) +
tm_polygons()+
tm_fill("percent", style = "quantile", n=5, palette = "Reds", title = "Hypertension prevalence") +
tm_borders(alpha = .4)+
tm_compass() +
tm_text("NAME_1") +
tm_layout(title = "South AFRICA, DHIS2016",
legend.text.size = 0.5,
legend.title.size =0.5 ,
legend.position = c("right", "bottom"),
frame = FALSE)p.w$weights
## [[1]]
## [1] 0.25 0.25 0.25 0.25
##
## [[2]]
## [1] 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667
##
## [[3]]
## [1] 0.25 0.25 0.25 0.25
##
## [[4]]
## [1] 0.3333333 0.3333333 0.3333333
##
## [[5]]
## [1] 0.3333333 0.3333333 0.3333333
##
## [[6]]
## [1] 0.25 0.25 0.25 0.25
##
## [[7]]
## [1] 0.25 0.25 0.25 0.25
##
## [[8]]
## [1] 0.25 0.25 0.25 0.25
##
## [[9]]
## [1] 0.5 0.5
##
## attr(,"mode")
## [1] "binary"
## attr(,"W")
## [1] TRUE
## attr(,"comp")
## attr(,"comp")$d
## [1] 4 6 4 3 3 4 4 4 2p$NAME_1[w[[1]]]
## [1] "Free State" "KwaZulu-Natal" "Northern Cape" "Western Cape"
1/4
## [1] 0.25p$NAME_1[w[[2]]]
## [1] "Eastern Cape" "Gauteng" "KwaZulu-Natal" "Mpumalanga"
## [5] "North West" "Northern Cape"
1/6
## [1] 0.1666667p$NAME_1[w[[3]]]
## [1] "Free State" "Limpopo" "Mpumalanga" "North West"
1/4
## [1] 0.25p$NAME_1[w[[4]]]
## [1] "Eastern Cape" "Free State" "Mpumalanga"
1/3
## [1] 0.3333333Running a Spatial Autocorrelation
- Spatial autocorrelation measures how distance influences a particular variable. In other words, it quantifies the degree to which objects are similar to nearby objects. Variables are said to have positive spatial autocorrelation when similar values tend to be closer together than dissimilar values.
- Spatial autocorrelation is used to describe the extent to which a variable is correlated with itself through space
This aligns with Tobler’s First Law of Geography, which states:
“Everything is related to everything else, but near things are more related than distant things.”
We would therefore expect most geographic phenomena to exhibit some degree of spatial autocorrelation. In population data, this is often observed because people with similar characteristics tend to reside in similar neighborhoods due to factors such as house prices, proximity to workplaces, and cultural influences.
- Positive spatial autocorrelation occurs when observations with similar values are closer together (i.e., clustered). Negative spatial autocorrelation occurs when observations with dissimilar values are closer together (i.e., dispersed). Figure 8.1 shows three configurations of areas showing different types of spatial autocorrelation.
Spatial Autocorrelation and Moran’s \(I\) coefficient
A convenient modification to the concept of the spatial moving average is as follows. Instead of using the variable \(x\) for the calculation of the spatial moving average, we first center it on the global mean: \[ z_i = x_i - \bar{x} \]
In this way, the values of \(z_i\) are given in deviations from the mean. By forcing the variable to be centered on the mean, the slope of the fit line is forced to pass through the origin.
Calculate the mean-centered version of percent, and then its spatial moving average:
(df_mean_center_scatterplot <- transmute(p, # Modify values in dataframe
Density_z = percent - mean(percent),
SMA_z = lag.listw(p.w, Density_z),
SMA_y = lag.listw(p.w, p$percent)))| Density_z | SMA_z | SMA_y | geometry |
|---|---|---|---|
| 1.6 | 3.325000 | 23.62500 | MULTIPOLYGON (((25.64375 -3… |
| 4.3 | -1.000000 | 19.30000 | MULTIPOLYGON (((27.98611 -2… |
| -4.8 | -1.450000 | 18.85000 | MULTIPOLYGON (((28.75139 -2… |
| -4.8 | 0.600000 | 20.90000 | MULTIPOLYGON (((31.63736 -2… |
| -6.9 | -2.666667 | 17.63333 | MULTIPOLYGON (((29.66671 -2… |
| -4.1 | -3.050000 | 17.25000 | MULTIPOLYGON (((31.87835 -2… |
| 0.9 | -0.550000 | 19.75000 | MULTIPOLYGON (((26.40328 -2… |
| 5.2 | 3.850000 | 24.15000 | MULTIPOLYGON (((16.99514 -2… |
| 8.6 | 3.400000 | 23.70000 | MULTIPOLYGON (((19.66764 -3… |
In General
- we can turn ….
p.w$weights
## [[1]]
## [1] 0.25 0.25 0.25 0.25
##
## [[2]]
## [1] 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667
##
## [[3]]
## [1] 0.25 0.25 0.25 0.25
##
## [[4]]
## [1] 0.3333333 0.3333333 0.3333333
##
## [[5]]
## [1] 0.3333333 0.3333333 0.3333333
##
## [[6]]
## [1] 0.25 0.25 0.25 0.25
##
## [[7]]
## [1] 0.25 0.25 0.25 0.25
##
## [[8]]
## [1] 0.25 0.25 0.25 0.25
##
## [[9]]
## [1] 0.5 0.5
##
## attr(,"mode")
## [1] "binary"
## attr(,"W")
## [1] TRUE
## attr(,"comp")
## attr(,"comp")$d
## [1] 4 6 4 3 3 4 4 4 2- into a matrix
(Wmat <- listw2mat(p.w))
## 1 2 3 4 5 6 7 8
## 1 0.0000000 0.2500000 0.0000000 0.2500000 0.00 0.0000000 0.0000000 0.2500000
## 2 0.1666667 0.0000000 0.1666667 0.1666667 0.00 0.1666667 0.1666667 0.1666667
## 3 0.0000000 0.2500000 0.0000000 0.0000000 0.25 0.2500000 0.2500000 0.0000000
## 4 0.3333333 0.3333333 0.0000000 0.0000000 0.00 0.3333333 0.0000000 0.0000000
## 5 0.0000000 0.0000000 0.3333333 0.0000000 0.00 0.3333333 0.3333333 0.0000000
## 6 0.0000000 0.2500000 0.2500000 0.2500000 0.25 0.0000000 0.0000000 0.0000000
## 7 0.0000000 0.2500000 0.2500000 0.0000000 0.25 0.0000000 0.0000000 0.2500000
## 8 0.2500000 0.2500000 0.0000000 0.0000000 0.00 0.0000000 0.2500000 0.0000000
## 9 0.5000000 0.0000000 0.0000000 0.0000000 0.00 0.0000000 0.0000000 0.5000000
## 9
## 1 0.25
## 2 0.00
## 3 0.00
## 4 0.00
## 5 0.00
## 6 0.00
## 7 0.00
## 8 0.25
## 9 0.00\[y=\rho Wy+ \epsilon\]
Matrix Multiplication
(y_lag <- as.numeric(Wmat %*% p$percent))
## [1] 23.62500 19.30000 18.85000 20.90000 17.63333 17.25000 19.75000 24.15000
## [9] 23.70000- if we use \(z_i\) values we get \(z=\rho Wz+ \epsilon\)
(z_lag <-as.numeric(Wmat %*% df_mean_center_scatterplot$Density_z))
## [1] 3.325000 -1.000000 -1.450000 0.600000 -2.666667 -3.050000 -0.550000
## [8] 3.850000 3.400000Moran’s \(I\) and Moran’s Scatterplot
Based on the discussion above, let us define the following coefficient, called Moran’s I:
- this coefficient of spatial autocorrelation was derived based on the idea of aggregating the products of a (mean-centered) variable by its spatial moving average, and then dividing by the variance: \[ I = \frac{\sum_{i=1}^n{z_i\sum_{j=1}^n{w_{ij}^{st}z_j}}}{\sum_{i=1}^{n}{z_i^2}} \]
The numerator in this expression is the sum of the products described above. The denominator is the variance of variable \(x_i\), and is used here to scale Moran’s \(I\) so that it is contained roughly in the interval \((-1, 1)\) (the exact bounds depend on the characteristics of the zoning system).
Moran’s \(I\) is a coefficient of spatial autocorrelation.
We can calculate Moran’s \(I\) as follows, using as an example the mean-centered population density (notice how it is the sum of the products of \(z_i\) by their spatial moving averages \(\bar{z}_i\), divided by the variance):
sum(df_mean_center_scatterplot$Density_z*z_lag)/sum(df_mean_center_scatterplot$Density_z^2)
## [1] 0.3632585sum(df_mean_center_scatterplot$Density_z * df_mean_center_scatterplot$SMA_z) / sum(df_mean_center_scatterplot$Density_z^2)
## [1] 0.3632585Since the value is positive, and relatively high, this would suggest a non-random spatial pattern of similar values (i.e., high & high and low & low).
Moran’s \(I\) is implemented in R in the spdep package, which makes its calculation easy, since you do not have to go manually through the process of calculating the spatial moving averages, etc.
The function moran() requires as input arguments a variable, a set of spatial weights, the number of zones (\(n\)), and the total sum of all weights (termed \(S_0\)) - which in the case of row-standardized spatial weights is equal to the number of zones. Therefore:
Global Moran’s I In General
The Global Moran’s I statistic (Moran, 1950) is defined as:
\[ I = \frac{n \sum_{i}\sum_{j} w_{ij}(Y_i - \bar{Y})(Y_j - \bar{Y})} {\left(\sum_{i \neq j} w_{ij}\right)\sum_i (Y_i - \bar{Y})^2}, \]
where
- \(n\)is the number of regions,
- \(Y_i\)is the observed value of the variable of interest in region \(i\),
- \(\bar{Y}\)is the mean of all values, and
- \(w_{ij}\)are spatial weights that denote the spatial proximity between regions \(i\)and \(j\), with \(w_{ii} = 0\).
The definition of the spatial weights depends on the variable of study and the specific setting.
Expected value and variance
Under the null hypothesis of no spatial autocorrelation, the observations \(Y_i\)are independent and identically distributed. In this case, Moran’s I is asymptotically normally distributed with
\[ E[I] = -\frac{1}{n-1}, \]
and
\[ Var[I] = \frac{n^2 S_1 - n(n-1)S_2 - 2S_0^2}{(n-1)(n+1)S_0^2}, \]
where
- \(S_0 = \sum_{i \neq j} w_{ij},\)
- \(S_1 = \tfrac{1}{2}\sum_{i \neq j} (w_{ij} + w_{ji})^2,\)
- \(S_2 = \sum_{k}\left(\sum_j w_{kj} + \sum_i w_{ik}\right)^2.\)
Interpretation
- Moran’s I values usually range from –1 to 1.
- Values significantly above \(E[I]\)indicate positive spatial autocorrelation (clustering).
- Values significantly below \(E[I]\)indicate negative spatial autocorrelation (dispersion).
- Values close to \(E[I]\)indicate randomness (no spatial pattern).
Hypothesis testing
When \(n\)is sufficiently large, I has an approximate normal distribution. We can test spatial autocorrelation with the statistic:
\[ z = \frac{I - E[I]}{\sqrt{Var[I]}}. \]
- Null hypothesis: \(H_0: I = E[I]\)(no spatial autocorrelation)
- Alternative hypothesis: \(H_1: I \neq E[I]\)(spatial autocorrelation)
At a chosen significance level \(\alpha\):
- If \(p\text{-value} < \alpha\), reject \(H_0\).
- If \(p\text{-value} \geq \alpha\), fail to reject \(H_0\).
Hypothesis Testing for Spatial Autocorrelation in R
The tools described so far are useful to suggest whether a pattern is random; however, while inspection of the scatterplot is suggestive, we would like a more formal criterion to decide whether the pattern is random. Fortunately, Moran’s \(I\) can be used to develop a test of hypothesis. The expected value of Moran’s \(I\) under the null hypothesis of spatial randomness (or independence), as well as its variance, have been derived.
A test for autocorrelation based on Moran’s \(I\) is implemented in the spdep package:
#"moran.test" is calculating spatial autocorrelation of population density in Hamilton census tracts
(mc<-moran.test(p$percent, p.w))
##
## Moran I test under randomisation
##
## data: p$percent
## weights: p.w
##
## Moran I statistic standard deviate = 2.5311, p-value = 0.005685
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.36325848 -0.12500000 0.03721111Since the null hypothesis is of spatial independence, the \(p\)-value of the statistic is interpreted as the probability of making a mistake by rejecting the null hypothesis. In the present case, the \(p\)-value is such a small number that we can reject the null hypothesis with a high degree of confidence.
You can verify that this matches the value calculated above. The kind of scatterplots that we used previously are called Moran’s scatterplots, and they can also be created easily by means of the moran.plot() function of the spdep package:
# Confirming the results from the Moran coefficient above. We use "moran.plot" to illustrate the SMA of population density by census tract in Hamilton.
mp <- moran.plot(p$percent, p.w,xlab = "Percent", ylab = "Lagged Percent")Monte Carlo randomization
An alternative to the normal approximation is Monte Carlo randomization:
- Randomly permute observed values across regions,
- Compute Moran’s I for each permutation,
- Compare the observed I to this reference distribution.
If the observed I lies in the tails of the distribution, the null hypothesis of independence is rejected.
Moran’s \(I\) and Moran’s scatterplots are among the most widely used tools in the analysis of spatial area data.
gmoranMC <- moran.mc(p$percent, p.w, nsim = 999)
gmoranMC
##
## Monte-Carlo simulation of Moran I
##
## data: p$percent
## weights: p.w
## number of simulations + 1: 1000
##
## statistic = 0.36326, observed rank = 986, p-value = 0.014
## alternative hypothesis: greaterReferences
- Allaire, JJ. 2022. Quarto: R Interface to “Quarto” Markdown Publishing System. https://CRAN.R-project.org/package=quarto.
- Anselin, Luc. 1995. “Local Indicators of Spatial Association - LISA.” Geographical Analysis 27: 93–115. https://doi.org/https://doi.org/10.1111/j.1538-4632.1995.tb00338.x.