I'm reasonably new to R and I am trying to rasterize the output of spdep's localG function. This code:
neigh2<-dnearneigh(profcurvPts, 0, 2)
list<-nb2listw(neigh2)
gistar<-localG(profcurvPts$layer, list)
girast<-rasterize(gistar, profcurv)
Yields an error unable to find an inherited method for function 'rasterize' for signature '"localG", "RasterLayer"'
I have tried changing the localG class to a data.frame, but it creates a 1 column matrix that still won't rasterize.
To sum it up: what should I do to get a raster of the localG output?
Thanks in advance!
You are trying to call an object of class localG
which has no associated method for sp or raster classes. Here is a workflow for rasterizing a local G result.
First, add packages and data. The meuse object is of SpatialPointsDataFrame and meuse.grid starts as SpatialGridDataFrame but is coerced into a rasterLayer object for rasterizing the point data.
library(spdep)
library(raster)
data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
proj4string(meuse.grid) <- CRS("+init=epsg:28992")
gridded(meuse.grid) = TRUE
meuse.grid <- raster(meuse.grid)
Here we conduct the local G analysis.
nb <- dnearneigh(coordinates(meuse), 0, 500)
G <- localG(meuse$cadmium, nb2listw(nb, style="B"))
This is where we can coerce the localG results, join them to the point data and rasterize the results. You can use as.numeric
for coercing from a localG object (basically a list object). Please read the help for raster::rasterize
. The x
argument requires SpatialPoints or a matrix of coordinates, y
is a rasterLayer object to provide the raster dimensions and field
represents the attribute that is being rasterized. If you need a background value for the raster that is other than NA then use the background
argument.
meuse$G <- as.numeric(G)
spplot(meuse, "G")
Gr <- rasterize(coordinates(meuse), meuse.grid, field = meuse$G, background = NA)