date()
## [1] "Wed Feb 12 11:27:13 2014"
Use the Columbus, OH crime data from http://myweb.fsu.edu/jelsner/data/columbus.zip.
require(maptools) require(rgdal) download.file(“http://myweb.fsu.edu/jelsner/data/columbus.zip”, “columbus.zip”, mode = “wb”) unzip(“columbus.zip”) CC = readOGR(dsn = “.”, layer = “columbus”)
slotNames(CC) str(CC, max.level=2) head(CC@data) df = CC@data
plot(CC) spplot(CC, “CRIME”, pretty = TRUE) require(RColorBrewer) range(CC$CRIME) rng = seq(0, 70, 10) cls = brewer.pal(7, “Greens”) spplot(CC, “CRIME”, col.regions=cls, at=rng,sub = “Crime Data in Oho”)
require(spdep) CC.nb = poly2nb(CC) CC.wts = nb2listw(CC.nb) ##CALCULATE MORAN'S I m = length(CC$CRIME) s = Szero(CC.wts) moran(CC$CRIME, CC.wts, n = m, S0 = s) ##TEST FOR WEIGHTING STYLE moran.test(CC$CRIME, nb2listw(CC.nb, style = “W”))$estimate[1] moran.test(CC$CRIME, nb2listw(CC.nb, style = “B”))$estimate[1] # binary moran.test(CC$CRIME, nb2listw(CC.nb, style = “S”))$estimate[1] # variance-stabilizing
require(ggplot2) Wsids = lag.listw(CC.wts, CC$CRIME) dat = data.frame(CC = CC$CRIME, Wsids = Wsids) ggplot(dat, aes(x = CC, y = Wsids)) + geom_point() + geom_smooth(method = “lm”) + xlab(“Columbus Crime”) + ylab(“Spatial Lag of crime data”)
lm(Wsids ~ CC, data = dat)