Skip to content
Prev 1228 / 29559 Next

Linking lm residuls to specific polygon in shape files

On Mon, 14 Aug 2006, David Martell wrote:

            
lm.morantest() uses the whole "lm" object returned by lm(), so the 
residuals are by definition in the same order as the variables included in 
the model formula. If you need tight control, do something like this:

xx <- readShapePoly(system.file("shapes/columbus.shp", 
  package="maptools")[1], IDvar="NEIGNO")
row.names(as(xx, "data.frame"))
xx_nb <- poly2nb(as(xx, "SpatialPolygons"))
attr(xx_nb, "region.id")
lm_obj <- lm(CRIME ~ INC + HOVAL, data=xx)
names(residuals(lm_obj))
lm.morantest(lm_obj, nb2listw(xx_nb), spChk=TRUE)

where spChk=TRUE checks the equality of the names of the residuals of the 
"lm" object (taken from the data= object of the call to lm()) with the 
"region.id" attribute of the neighbour list. From the time the sapefile is 
read, it has nothing more to do with the SpatialPolygonsDataFrame object 
(here xx). Doing something like:

xx$lm_obj_resids <- residuals(lm_obj)

and then

writePolyShape(xx, "newshape")

includes them in a new shapefile.

Does this clarify things?

Roger