1

I have a SpatialLinesData frame with 1657 different routes. Each route is of a different length and has a differing number of nodes or waypoints (lat, lon).

For example, routes@line[[87]] is made up of 7 waypoints. I am wondering if there is a simple method to extract the lat, lon coordinates, or [,1] and[,2] of every route and convert them into a list of 1657.

When I try this with one routes@line[[87]], for example, I get an error:

    > as.list(routes@lines[[87]])
    Error in as.list.default(routes@lines[[87]]) : 
      no method for coercing this S4 class to a vector

Does a method exist for converting line objects to lists?

    > 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

    > routes@lines[[87]]
    An object of class "Lines"
    Slot "Lines":
    [[1]]
    An object of class "Line"
    Slot "coords":
              [,1]     [,2]
    [1,] -79.92976 43.25867
    [2,] -79.92984 43.25865
    [3,] -79.92986 43.25868
    [4,] -79.92989 43.25870
    [5,] -79.92983 43.25871
    [6,] -79.92983 43.25871
    [7,] -79.92983 43.25871



    Slot "ID":
    [1] "87"
2

Just pipe the data into an empty list using a double bracket index.

routes.list <- list()
for(i in 1:nrows(routes)) { routes.list[[i]] <- routes@lines[[i]] }

If you only want the coordinates and not the spatial object, just wrap each line in a call to coordinates such; coordinates(routes[i,])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.