[R-sig-Geo] split/divide SpatialLines (sp) into n segments
Roger Bivand
Roger.Bivand at nhh.no
Wed Apr 10 10:12:38 CEST 2013
On Tue, 9 Apr 2013, Omphalodes Verna wrote:
> Dear list!
>
> I would like to split/divide SpatialLines into n segments. Is there any function to do this in R? Or does somebody know the solution for that?
>
> Here is example of SpatialLines from the sp vignette:
>
> library(sp)
> Sl = SpatialLines(list(Lines(list(Line(cbind(c(1,2,3),c(3,2,2)))), ID="a")))
> plot(Sl)
> coordinates(Sl)
Assuming the line segents are to be Lines objects:
library(sp)
Sl = SpatialLines(list(Lines(list(Line(cbind(c(1,2,3),c(3,2,2)))),
ID="a")))
cSl <- coordinates(Sl)
cSl
in_nrows <- lapply(cSl, function(x) sapply(x, nrow))
outn <- sapply(in_nrows, function(y) sum(y-1))
res <- vector(mode="list", length=outn)
i <- 1
for (j in seq(along=cSl)) {
for (k in seq(along=cSl[[j]])) {
for (l in 1:(nrow(cSl[[j]][[k]])-1)) {
res[[i]] <- cSl[[j]][[k]][l:(l+1),]
i <- i + 1
}
}
}
res1 <- vector(mode="list", length=outn)
for (i in seq(along=res))
res1[[i]] <- Lines(list(Line(res[[i]])), as.character(i))
outSL <- SpatialLines(res1)
It would be possible to use *apply functions instead of the loops, but the
loops may make the operations plainer. To show that we can reconstruct the
input object (not the same ID, but the geometry is OK):
library(rgeos)
coordinates(gLineMerge(outSL))
Hope this helps,
Roger
>
> Thanks to all, OV
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>
--
Roger Bivand
Department of Economics, NHH Norwegian School of Economics,
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