[GIS] Merge a list of SpatialLines

rsp

I started off with a SpatialPointsDataFrame, containing locations from animals wearing GPS loggers. Aside from the coordinates, the data frame also contains the animals' ID and a timestamp.

From this SpatialPointsDataFrame, I created lines that show the trajectory of each animal over the tracking period. I've used the following code:

spdf4tri#the SpatialPointsDataFrame

ids=unique(spdf4tri$id)
trajectory <- list()
 for (i in ids){ 
   spdf4bird<-subset(spdf4tri, id==i)
   birdtrajectory<-SpatialLines(list(Lines(list(Line(spdf4bird)), "id")))
   trajectory[[i]]<-birdtrajectory
   print(i)
 }

Now, I have a problem, because trajectory is of the class 'list'. I cannot figure out how to unlist it.

Best Answer

As I mentioned in my comment, you can use do.call for this. Here is an example.

First, add sp library and create a list with three SpatialLines objects (would work with Lines object as well).

library(sp)
sp.lines <- list()
  sp.lines[[1]] <- SpatialLines(list(Lines(list(Line(cbind(c(1,2,3),c(3,2,2)))),ID="a"))) 
  sp.lines[[2]] <- SpatialLines(list(Lines(list(Line(cbind(c(1,2,3)+0.5,c(3,2,2)+0.5))),ID="b"))) 
  sp.lines[[3]] <- SpatialLines(list(Lines(list(Line(cbind(c(1,2,3),c(1,1.5,1)))),ID="c"))) 

Now, use do.call with rbind to merge the lines into a single SpatialLines object.

merged.lines <- do.call(rbind, sp.lines)
  class(merged.lines)
  length(merged.lines)
  plot(merged.lines, col=1:3)