I have two problems.
Problem 1: I would like to delete all cells of the grid whose centroid is not located over the raster. I'm not even sure if I'm working with the right "types of objects" (RasterLayer, SpatialPixels, etc.).
See example with dummy data below:
# Load package
library(raster)
# Create raster and define coordinate reference system
ras <- raster(nrows = 100, ncol = 100, xmn = 0, xmx = 100, ymn = 0, ymx = 100)
proj4string(ras) <- CRS("+init=epsg:32198")
# Generate random values
val <- sample(x = 1:100, size = ncell(ras), replace = T)
values(ras) <- val
# Create effort grid
xym <- matrix(c(-30,130,130,-30,-30,-30,130,130), nrow = 4, ncol = 2)
p <- Polygon(xym)
ps <- Polygons(list(p), 1)
sps <- SpatialPolygons(list(ps))
proj4string(sps) <- CRS("+init=epsg:32198")
data <- data.frame(f = 99.9)
spdf <- SpatialPolygonsDataFrame(sps, data)
ptsreg <- spsample(spdf, 50, type = "regular")
grid <- SpatialPixels(ptsreg)
# Plot raster over grid
plot(grid)
plot(ras, add = T)
Problem 2: Is there another way to create an effort grid? My code works but I'm pretty sure there's a simpler way?
Also... In this example, I plotted the grid first and added the raster. If I do it the other way (raster first and grid second), the resulting plot doesn't show the whole extent of the grid.
How can I plot the grid over the raster but still show the entire grid? Such as: