lag.listw creates incorrect spatial lag values when I use the function spdep::cell2nb. I have a raster file and want to create a new raster where each cell has the average value of its neighboring cells (spatial lag value).
The code below creates
- a new raster from scratch and
- calculates the neighbor matrix with cell2nb.
- nb2listw constructs the weights that accord to each neighbor value.
- lag.listw creates the vector of neighbor values
- Finally I use this vector to create a new raster.
Code:
library(raster)
library(spdep)
##raster
r<-raster(nrows=7, ncols=8)
##raster values
v<-rep(0,ncell(r))
i<-sample(1:ncell(r),1)
v[i]<-1
values(r)<-v
plot(r)
##neighbor values
#neighbor list
nb<-cell2nb(nrow=nrow(r),ncol=ncol(r),type="queen")
#spatial weights matrix
nb.w<-nb2listw(nb,style="W", zero.policy=T)
#lagged values
nb.v<-lag.listw(nb.w,values(r),zero.policy=T,NAOK=T)
##new raster
nb.r<-r
values(nb.r)<-nb.v
plot(nb.r)
The new raster with neighbor values is:
Comparing both images it becomes clear that this method values are misplaced and wrong.
The above code works only if the given raster/ cell-matrix has equal numbers of rows and columns. Test:
##raster
r<-raster(nrows=8, ncols=8)
##raster values
v<-rep(0,ncell(r))
i<-sample(1:ncell(r),1)
v[i]<-1
values(r)<-v
plot(r)
##neighbor values
#neighbor list
nb<-cell2nb(nrow=nrow(r),ncol=ncol(r),type="queen")
#spatial weights matrix
nb.w<-nb2listw(nb,style="W", zero.policy=T)
#lagged values
nb.v<-lag.listw(nb.w,values(r),zero.policy=T,NAOK=T)
##new raster
nb.r<-r
values(nb.r)<-nb.v
plot(nb.r)
Use the
focal
function from theraster
package itself. It statistics based on the neighboring cell values and the own cell value. To exclude the own cell value from this calculation you have to 1) attribute a zero weight to it and 2) adapt the mean function to have one observation less.the weight matrix must have a zero value for the own value:
To take the avereage of all neighboring cells (withoug the own cell value) you can create your own funciton:
To take into account, that edges have fewer neighbors you can adjust the weights with:
With either of these functions you can now create a new raste containing the spatial lags:
base raster plot
spatial lag raster plot