Skip to content

Coercing spatstat::psp to sp:SpatialLines

5 messages · Roger Bivand, Mathieu Rajerison, Rolf Turner

#
On Tue, 15 Nov 2011, Mathieu Rajerison wrote:

            
The coercion functions in maptools, contributed by Adrian Baddeley, go 
from SpatialLines to psp, not the reverse. You need to create the set of 
coercion methods to go the other way - contributions welcome!

Roger

  
    
#
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