0

I´m trying to follow the tutorial "Handling shape files in the spatstat package" by Adrian Baddeley where a shape as SpatialPolygonsDataFrame is converted to a collection of owin´s.

The key attributes of shape are summarized below and my objective is to test whether a collection of points are within a collection of polygons.

summary(shape)

Object of class SpatialPolygonsDataFrame
Coordinates:
        min       max
x -43.13679 -42.95351
y -22.98961 -22.85380
Is projected: FALSE 
proj4string : [+proj=longlat +ellps=GRS80 +no_defs]

it has 907 polygons here are the suggested transformations

cp <- as(shape, "SpatialPolygons")
cregions <- slot(cp, "polygons")
cregions <- lapply(cregions, function(x) { SpatialPolygons(list(x)) })
cwindows <- lapply(cregions, as.owin)

but I get the error

Error in as.owin.default(X[[1L]], ...) : Can't interpret W as a window

Any ideas? Thanks

Joao Carlos
  • 27
  • 1
  • 4
  • What do you get for `class(cregions)` ? There may be something unintended in your conversion to `SpatialPolygons` or from there to `polygons` . – Carl Witthoft Oct 04 '13 at 14:50

2 Answers2

0

I got the exact same error message:

class(cregions[[1]])

[1] "SpatialPolygons" attr(,"package") [1] "sp"

I think it has to do with errors in topology. I got it to work with this (abeit homemade) function:

fixholes = function(sp.obj) {
  require(rgeos)
  require(stringr)
  if(!inherits(sp.obj, "SpatialPolygons")) stop("Input object must be of class SpatialPolygons")
  pls = slot(sp.obj, "polygons")
  pls1 = lapply(pls, checkPolygonsHoles)
  slot(sp.obj, "polygons") = pls1
  return(sp.obj)
}

I then created a function to employ Adrian Baddeley's routine detailed in "Handling shapefiles in the spatstat package":

spdf2owin = function(spdf) {
  cp <- as(spdf, "SpatialPolygons")
  cregions <- slot(cp, "polygons")
  cregions <- lapply(cregions, function(x) { fixholes(SpatialPolygons(list(x))) })
  cwindows <- lapply(cregions, as.owin)
  ch <- hyperframe(window=cwindows)
  ch <- cbind.hyperframe(ch, spdf@data)
  return(ch)
}

For example,

cregions = spdf2owin(columbus)

Worked for me!

tbogg
  • 1
0

The package maptools must be loaded in order to convert sp classes to spatstat classes.

as.owin is a generic function defined in spatstat. Some methods for as.owin are provided in spatstat; other methods are provided in maptools. In order to convert a SpatialPolygons to an owin, the method as.owin.SpatialPolygons must be available, and this is provided by maptools. If maptools is not loaded, the call to as.owin will dispatch to as.owin.default and give the error message which you got.

Adrian Baddeley
  • 1,956
  • 1
  • 8
  • 7