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)