9.1 Analysing Patterns Toolset
For this chapter, you will need the following R Packages:
library(arc2r)
library(sf)
library(ggplot2)
9.1.1 Spatial Autocorrelation (Global Morans I)
Here’s the function to calculate Morans I
<- function(sf_object, col) {
morans_i require(sf)
<- nrow(sf_object)
n <- unlist(st_set_geometry(sf_object, NULL)[, col], use.names = FALSE)
y <- mean(y, na.rm = TRUE)
ybar <- y - ybar
dy <- sum(dy^2, na.rm = TRUE)
dy_sum <- n/dy_sum
vr <- st_touches(sf_object, sparse = FALSE)
w <- tcrossprod(dy)
pm <- pm * w
pmw <- sum(pmw, na.rm = TRUE)
spmw <- sum(w, na.rm = TRUE)
smw <- spmw/smw
sw <- vr * sw
MI
MI }
data("zweitwohnung_gemeinden")
<- st_set_crs(zweitwohnung_gemeinden, 2056) zweitwohung
<- ggplot(zweitwohung) + geom_sf(aes(fill = ja_in_percent), colour = NA) +
zweit_plot scale_fill_gradient2(low = "#2c7bb6", mid = "#ffffbf", high = "#d7191c", midpoint = 50,
breaks = c(0, 25, 50, 75, 100), limits = c(0, 100)) + labs(title = "Results from the 'Zweitwohungsinitiative'",
subtitle = "Percent in Approval", fill = "") + theme_void() + theme(legend.position = "bottom")
zweit_plot
morans_i(zweitwohung, "ja_in_percent")
## [1] 0.6304227