识别规则格子中的哪些点在多边形的边界内

Identifying which points in a regular lattice are within a polygon's boundaries

我想计算出定义规则格子的哪些点位于多边形内。下面的代码执行此操作但非常非常慢:

#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) 

考虑到思考时间和计算时间,有没有更快的方法?

是的,有更好的方法。对于此操作和许多其他拓扑操作,rgeos 程序包已为您提供了很好的帮助。在这里,你想要 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)