At the moment I am having some difficulties with calculating a spatial lag in R
.
I know how to calculate the lag in space-wide format but am unable to do it in long form, i.e. have repeated observations for the unit of analysis.
Below is some mock data to illustrate what I am trying to do. Let's start by generating some observations of events that I'm interested in.
# Create observations
pts<-cbind(set.seed(2014),x=runif(30,1,5),y=runif(30,1,5),
time=sample(1:5,30,replace=T))
require(sp)
pts<-SpatialPoints(pts)
x
and y
are the coordinates while time
represents the time period in which the event takes place. The events need to be aggregated to polygons which is the unit of analysis. In this example the polygons are grid-cells and for simplicity the boundaries are fixed over time.
# Observations take place in different areas; create polygons for areas
X<-c(rep(1,5),rep(2,5),rep(3,5),rep(4,5),rep(5,5))
Y<-c(rep(seq(1,5,1),5))
df<-data.frame(X,Y)
df$cell<-1:nrow(df) # Grid-cell identifier
require(raster)
coordinates(df)<-~X+Y
rast<-raster(extent(df),ncol=5,nrow=5)
grid<-rasterize(df,rast,df$cell,FUN=max)
grid<-rasterToPolygons(grid) # Create polygons
We can plot the data just to get an overview of the distribution:
For space-wide format I would calculate the spatial lag the following way:
pointsincell=over(SpatialPolygons(grid@polygons),SpatialPoints(pts),
returnList=TRUE)
grid$totalcount<-unlist(lapply(pointsincell,length))
require(spdep)
neigh<-poly2nb(grid) # Create neighbour list
weights<-nb2listw(neigh,style="B",zero.policy=TRUE) # Create weights (binary)
grid$spatial.lag<-lag.listw(weights,
grid$totalcount,zero.policy=TRUE) # Add to raster
However, as you can see doing it this way doesn't take into account the fact that the events happen at different moments at time. It just simply aggregates everything to the polygon level. Now I want to calculate this spatial-lag taking into account this temporal dimension so aggregating the data in this case to the polygon-time level.
I wonder whether anyone has a useful suggestion on how this could be accomplished? What is the most convenient way of calculating spatial lags in long format?
I had a look at the spacetime
package but was unsuccessful in applying it.