Spatial neighbors

Spatial neighbors can be obtained using the spdep  package (by Roger Bivand and Luc Anselin).  Some preliminaries:

library(maptools)
library(RColorBrewer)
library(spdep)

## read a county outline shape file
orotl.shp <- readShapeLines(file.choose(),
     proj4string=CRS("+proj=longlat"))
attach(orstationc)

# station location matrix
orstationc.loc <- cbind(orstationc$lon, orstationc$lat)

# plot the county outline shape file and the variable
plot(orotl.shp, xlim=c(-125, -115), ylim=c(42,47))

# add climate station points
points(orstationc.loc, pch=16, cex=1.2)

Nearest-neighbor spatial neighbors, adjacency illustrated by line segments.

# k nearest neighbors
k <- 4
nn <- knearneigh(orstationc.loc, k, longlat=T)
orstationc.neighbors.knn <- knn2nb(nn)
plot(orstationc.neighbors.knn, orstationc.loc, add=T, lwd=2, col="green")

Distance-based neighbors

# distance neighbors
d <- 80
orstationc.neighbors.dist <- dnearneigh(orstationc.loc, 0, d, longlat=TRUE)
plot(orstationc.neighbors.dist, orstationc.loc, add=T, lwd=2, col="blue")

The spatial-neighbor object can be summarized using the summary() function, which provides information on the nature of the links among points.

# summary description of a spatial-neighbor object
summary(orstationc.neighbors.dist, orstationc.loc)

In addition looking at the first-order lags, it is also possible to look at second and higher-order lags:

# plotting second-order lags
col.lags <- nblag(orstationc.neighbors.knn, 2)
plot(col.lags[[2]], orstationc.loc, add=T, lwd=2, col="red", lty=2)

The spatial-neighbors matrix can be visualized using the nb2mat() and image() functions:

# spatial weights matrix
w.cols <- 1:92
w.rows <- 1:92

w.mat.knn <- nb2mat(orstationc.neighbors.knn, zero.policy=TRUE)
image(w.cols, w.rows, w.mat.knn, col=brewer.pal(3,"BuPu"))

w.mat.dist <- nb2mat(orstationc.neighbors.dist, zero.policy=TRUE)
image(w.cols, w.rows, w.mat.dist,col=brewer.pal(9,"BuPu"))