Skip to content
Prev 13411 / 29559 Next

Coercing spatstat::psp to sp:SpatialLines

On 16/11/11 20:49, Mathieu Rajerison wrote:
I hacked your code a bit and came up with the following:

# Generic function for S3 method:
as.SpatialLines <- function(from) {
UseMethod("as.SpatialLines")
}

# Method for class "psp".
as.SpatialLines.psp <- function (from) {
foo <- function(i,x){
     y <- matrix(unlist(x[i,]),2,2,byrow=TRUE)
     Lines(list(Line(y)),ID=i)
}
coords <- from$ends
SpatialLines(lapply(1:nrow(coords),foo,x=coords))
}

After sourcing in these two functions, try:

check <- as.SpatialLines(aix.psp)

and then compare:

all.equal(check,aix.lines) # Should get TRUE!!!

I *thought* that after having defined as.SpatialLines.psp() as above I would
be able to do:

     check <- as(aix.psp,"SpatialLines")

but that gave me the error

Error in as(aix.psp, "SpatialLines") :
   no method or default for coercing "psp" to "SpatialLines"

even though I had just written such a method!  There must be some extra
S4 classes and methods magic required here, that I don't know about.

Roger?

(I never touch S4 classes and methods with a sterilised barge-pole!)

     cheers,

         Rolf