[R-sig-Geo] Can you query points with a polygon?
adrian at maths.uwa.edu.au
Thu Dec 14 02:06:46 CET 2006
Ken Pierce writes:
> If I have a set of points from a shapefile (or generated in R) and a
> polygon from a shapefile, can I use the polygon to select the points
> that fall within it? One of the many packages must do it but I can't
> seem to figure which one.
Both splancs and spatstat can do this.
In spatstat you can use either the subset operator for point patterns [.ppp
or the low level function inside.owin. The polygon should first be
converted to an object of class "owin", e.g.
W <- owin(poly=list(x=xp, y=yp))
where xp and yp are vectors of coordinates of the vertices of the polygon
traversed in anticlockwise order; see help(owin).
You can then determine which points are inside the polygon by
ok <- inside.owin(x, y, W)
where x and y are vectors of coordinates of the points.
The return value is a logical vector that is TRUE when the
corresponding point lies inside the polygon.
If you want to select those points that are inside, you can of course
just take x[ok] and y[ok]. A more elegant way to do both steps is
to use the subset operator for point patterns, [.ppp
First convert your coordinate vectors into a point pattern object,
A <- ppp(x, y, range(x), range(y))
B <- A[W]
gets you the sub-pattern of points lying inside W.
This requires spatstat 1.10-2 or later.
More information about the R-sig-Geo