Coercing spatstat::psp to sp:SpatialLines
On 16/11/11 20:49, Mathieu Rajerison wrote:
Finally, I got a SpatialLines from a psp object (here named aix.psp)
Here's how I got it:
coords<- aix.psp$ends
nc<- nrow(coords)
out<- vector(mode="list", length=nc)
for (i in seq(along=out)) {
lLine<-Line(cbind(c(coords[i,1], coords[i,3]), c(coords[i,2],
coords[i,4])))
out[[i]]<- Lines(list(lLine), ID=i)
}
aix.lines<- SpatialLines(out)
I don't find my solution very elegant. I wondered if a simpler code could
be written using lapply function.
For that purpose, I did:
liste<-lapply(coords, function(x) Line(cbind(c(x[1], x[3]), c(x[2], x[4]))))
but I don't know how to create a list of this one, with an incrementating
ID, which is required for constructing a Lines object as
Lines(list(LineList), ID=i)
It's more a general R problem than an R-sig-geo one but if anyone here has
the issue, I would be thankful.
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