[R-sig-Geo] Sampling a grid from a single polygon

Roger Bivand Roger.Bivand at nhh.no
Wed Sep 5 21:45:29 CEST 2007


On Wed, 5 Sep 2007, Rob Schick wrote:

> Hi - I'm trying to write a simulation that loops over an animal movement
> track, creates a buffer at each x,y,t, and samples an underlying grid (sort
> of like Zonal Stats in ArcInfo).
>
> To create the polygon buffer centered on the current position and with
> radius r, I've written:
>
> poly <- function(x,y,r){
>    phi <- seq(0,2*pi,length.out=30)
>    xy <- matrix(NA, nrow=length(phi),ncol=2)
>        for(i in 1:length(phi)){
>            xy[i,1] <- x + (r * cos(phi[i]))
>            xy[i,2] <- y + (r * sin(phi[i]))
>        }
>    xy[i,1:2] <- xy[1,1:2]
>    xysp <- Polygon(xy,hole=F)
>    return(xysp)
> }
>
> Then calling it:
>
> test <- poly(xy[t,1], xy[t,2], 2)
>
> But when I try overlay(df,test), I get
>
>> overlay(df,test, fn=mean)
> Error in function (classes, fdef, mtable)  :
>        unable to find an inherited method for function "overlay", for
> signature "SpatialGridDataFrame", "Polygon"
>
>> class(df)
> [1] "SpatialGridDataFrame"
> attr(,"package")
> [1] "sp"
>
>> class(test)
> [1] "Polygon"
> attr(,"package")
> [1] "sp"
>
> I thought the error might be in the way I am calling df within overlay, but
> it's not clear from overlay-methods if this even possible. To test this, I
> tried
>
> overlay(as(df,"SpatialPoints"),test)
> Error in function (classes, fdef, mtable)  :
>        unable to find an inherited method for function "overlay", for
> signature "SpatialPoints", "Polygon"
>
> I also thought it might be a problem with using Polygon, instead of
> SpatialPolygons, but seems like I can't use the latter with a single
> polygon. Am I missing something easy?

Possibly:

SP <- SpatialPolygons(list(Polygons(list(test), ID="poly")))

that is, it needs to be a SpatialPolygons object. Since each Polygons 
object can contain one or more Polygon objects, and each SpatialPolygons
object can contain one or more Polygons objects, they need wrapping up in 
lists.

The overlay() methods should now work. If you want to use a canned circle, 
try disc() in the spatstat package - look for the bdry component 
containing a list of list of coordinates, which need closing.

Hope this helps,

Roger

>
> Thanks,
> Rob
>
>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no




More information about the R-sig-Geo mailing list