I am trying to make an out of-sample-prediction for spatial data using the spdep package. The documentation claims that this should be possible. However, I do not understand how it works. In particular I do not know how the spatial weights should be handled.
In the example below I generated data which I split into a training and a test set. How can I fit the model using the training data and predict the outcome of the test data?
library(spdep) set.seed(1) coords <- data.frame(x = runif(n=20, min =0, max = 10), y = runif(n=20, min = 0, max = 10)) sp_data <- SpatialPointsDataFrame(coords, data = data.frame(a = rnorm(20), b = rnorm(20) ) ) weights <- nb2listw(knn2nb(knearneigh(sp_data, k = 2), row.names = 1:20 )) #Using all data to fit the model sp_model <- lagsarlm(a ~ b, data = sp_data, listw = weights) in_sample <- predict(sp_model) #Using train set to fit the model train_set <- sp_data[1:15, ] #Out-of-sample prediction test_set <- sp_data[16:20, ]