2015-02-08 95 views
0

我想確定定義規則格的哪些點位於多邊形內。下面的代碼做到這一點,但非常非常緩慢:識別規則格中的哪些點位於多邊形的邊界內

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

考慮到雙方思考的時間和計算時間,有沒有這樣做的更快的方法?

回答

1

是的,有一個更好的方法。對於這個以及其他許多拓撲操作,您已經很好地涵蓋了這個包。在這裏,你想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) 

enter image description here

+0

優秀。非常感謝。 – JonMinton 2015-02-08 11:17:15