Prepare packages and data
# load libraries
library(maptools)
## Warning: package 'maptools' was built under R version 2.15.3
## Loading required package: foreign
## Loading required package: sp
## Loading required package: grid
## Loading required package: lattice
## Checking rgeos availability: FALSE Note: when rgeos is not available,
## polygon geometry computations in maptools depend on gpclib, which has a
## restricted licence. It is disabled by default; to enable gpclib, type
## gpclibPermit()
library(RANN)
library(spdep)
## Warning: package 'spdep' was built under R version 2.15.3
## Loading required package: boot
## Attaching package: 'boot'
## The following object(s) are masked from 'package:lattice':
##
## melanoma
## Loading required package: Matrix
## Loading required package: MASS
## Loading required package: nlme
## Loading required package: deldir
## deldir 0.0-21
## Loading required package: coda
## Warning: package 'coda' was built under R version 2.15.3
## Loading required package: splines
poverty <- readShapePoly(file.choose())
class(poverty)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
Creating neighbors
# create contiguity matrices
poverty_nbq <- poly2nb(poverty) #default is queen, creates queen
poverty_nbr <- poly2nb(poverty, queen = FALSE) #create rook
# choose the k nearest points as neighbors
coords <- coordinates(poverty)
FIPS <- row.names(as(poverty, "data.frame")) #define the fips code so we can use k nearest neighbors
poverty_kn1 <- knn2nb(knearneigh(coords, k = 1), row.names = FIPS) #create k nearest neighbors
poverty_kn2 <- knn2nb(knearneigh(coords, k = 2), row.names = FIPS)
poverty_kn4 <- knn2nb(knearneigh(coords, k = 4), row.names = FIPS)
# create distance based neighbors
# define distance
dist <- unlist(nbdists(poverty_kn1, coords))
summary(dist) #max is 1.466
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.0083 0.2800 0.3450 0.3720 0.4210 1.4700
# create max distance
max_k1 <- max(dist)
# create distance based matrix
poverty_kd1 <- dnearneigh(coords, d1 = 0, d2 = 0.75 * max_k1, row.names = FIPS)
poverty_kd2 <- dnearneigh(coords, d1 = 0, d2 = 1 * max_k1, row.names = FIPS)
poverty_kd3 <- dnearneigh(coords, d1 = 0, d2 = 1.5 * max_k1, row.names = FIPS)
# create weights matrices (row standard and binary), also exclude island
poverty_nbq_w <- nb2listw(poverty_nbq, zero.policy = T)
# use binary weights
poverty_nbq_wb <- nb2listw(poverty_nbq, style = "B", zero.policy = T)
# run moran's I test, using created weights
moran.test(poverty$PROPOV, listw = poverty_nbq_w, zero.policy = T)
##
## Moran's I test under randomisation
##
## data: poverty$PROPOV
## weights: poverty_nbq_w
##
## Moran I statistic standard deviate = 57.52, p-value < 2.2e-16
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.6194394 -0.0003224 0.0001161