---
title: "Making a prediction grid"
author: "D G Rossiter"
date: "`r Sys.Date()`"
output:
  html_document:
    theme: "lumen"
    code_folding: show
    fig_height: 4.5
    fig_width: 4.5
    fig_align: 'center'
---

This short note shows how to create a regular grid onto which kriging or another prediction method can be applied.

We use the Meuse dataset as an example of the study area we want to predict over. We have some points in this area:

```{r}
library(sp); library(gstat)
data(meuse)  # an example dataset supplied with the sp package
names(meuse)
coordinates(meuse) <- c("x", "y") # convert to a SpatialPointsDataFrame
summary(meuse)
bbox(meuse)
```

We can define any extent for a grid; here we choose to cover the bounding box, and expand the grid to match the chosen resolution.

```{r}
bbox(meuse)
res <- 120 # resolution
# round extremes to resolution
(x.min <- bbox(meuse)[1,1]%/%res*res)
(x.max <- (bbox(meuse)[1,2]+res)%/%res*res) # make sure it is outside the bbox
(y.min <- bbox(meuse)[2,1]%/%res*res)
(y.max <- (bbox(meuse)[2,2]+res)%/%res*res) # make sure it is outside the bbox
# grid of coordinates
grid <- expand.grid(x = seq(x.min, x.max, by=res),
              y = seq(y.min, y.max, by=res))
class(grid)
coordinates(grid) <- c("x", "y")
class(grid)
gridded(grid) <- T; fullgrid(grid) <- T
class(grid)
```

Now we can interpolate over the grid, here using IDW just to show a result:

```{r}
kres <- idw(zinc ~ 1, loc=meuse, newdata=grid)
spplot(kres, zcol="var1.pred")
```
