I would like to work out which points that define a regular lattice are within a polygon. The code below does this but VERY VERY slowly:
#the polygon that I want to check each point against
glasgow_single <- readShapePoly(
fn="data/clipped/glasgow_single"
)
#interpolated contains the coordinates of the regular grid
points_to_check <- expand.grid(
x=interpolated$x,
y=interpolated$y
)
#function to be called by plyr
fn <- function(X){
this_coord <- data.frame(lon=X["x"], lat=X["y"])
this_point <- SpatialPoints(this_coord)
out <- gContains(glasgow_single, this_point)
out <- data.frame(x=X["x"], y=X["y"], val=out)
return(out)
}
#plyr call
vals <- adply(points_to_check, 1, fn, .progress="text")
vals$val <- as.numeric(vals$val)
Taking into account both thinking time and computing time, is there a much faster way of doing this?
Yes, there's a much better approach. For this and many other topological operations, the rgeos package has you well covered. Here, you're wanting rgeos::gWithin()
:
## Required packages
library(rgdal)
library(raster) ## For example polygon & functions used to make example points
library(rgeos)
## Reproducible example
poly <- readOGR(system.file("external", package="raster"), "lux")[1,]
points <- as(raster(extent(poly)), "SpatialPoints")
proj4string(points) <- proj4string(poly)
## Test which points fall within polygon
win <- gWithin(points, poly, byid=TRUE)
## Check that it works
plot(poly)
points(points, col=1+win)