Search code examples
rgeor-spogr

Number of segments in SpatialLinesDataFrame


After importing a spatial lines dataframe with readOGR, I would like to determine the number of line segments (nodes) in each line. I cannot find a practical way to simply export the lengths as a vector.

routes@lines will get me to the line slots, but then how does one get the length of each one?

For example, in the sample data below, we see that the first line is composed of 93 segments, the second line composed of 170 segments, the third 91 segments, and so on.

In the end, I'd like a vector of 1657 numbers representing the length of line segments in the SpatialLinesDataFrame

Is there a quick solution?

> class(routes)
[1] "SpatialLinesDataFrame"
attr(,"package")
[1] "sp"
> str(routes)
Formal class 'SpatialLinesDataFrame' [package "sp"] with 4 slots
  ..@ data       :'data.frame': 1657 obs. of  3 variables:
  .. ..$ start_time: Factor w/ 1631 levels "2016/09/09 00:00:02",..: 1 2 3 4 5 6 7 8 9 10 ...
  .. ..$ duration  : int [1:1657] 786 1248 738 786 651 660 616 889 408 475 ...
  .. ..$ difftime  :Class 'difftime'  atomic [1:1657] 2 4 19 67 92 119 170 202 206 213 ...
  .. .. .. ..- attr(*, "units")= chr "secs"
  ..@ lines      :List of 1657
  .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots
  .. .. .. ..@ Lines:List of 1
  .. .. .. .. ..$ :Formal class 'Line' [package "sp"] with 1 slot
  .. .. .. .. .. .. ..@ coords: num [1:93, 1:2] -79.9 -79.9 -79.9 -79.9 -79.9 ...
  .. .. .. ..@ ID   : chr "0"
  .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots
  .. .. .. ..@ Lines:List of 1
  .. .. .. .. ..$ :Formal class 'Line' [package "sp"] with 1 slot
  .. .. .. .. .. .. ..@ coords: num [1:170, 1:2] -79.9 -79.9 -79.9 -79.9 -79.9 ...
  .. .. .. ..@ ID   : chr "1"
  .. ..$ :Formal class 'Lines' [package "sp"] with 2 slots
  .. .. .. ..@ Lines:List of 1
  .. .. .. .. ..$ :Formal class 'Line' [package "sp"] with 1 slot
  .. .. .. .. .. .. ..@ coords: num [1:91, 1:2] -79.9 -79.9 -79.9 -79.9 -79.9 ...
  .. .. .. ..@ ID   : chr "2"

Solution

  • Based on the output structure,

    sapply( routes@lines, function (x) dim(x@Lines[[1]]@coords)[1] )