How to unlist spatial objects and plot altogether in R
Asked Answered
D

1

2

I have spatial lines as 'list':

> SL1
[[1]]
class       : SpatialLines 
nfeatures   : 1 
extent      : 253641, 268641, 2621722, 2621722  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=46 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 

[[2]]
class       : SpatialLines 
nfeatures   : 1 
extent      : 253641, 268641, 2622722, 2622722  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=46 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 

[[3]]
class       : SpatialLines 
nfeatures   : 1 
extent      : 253641, 268641, 2623722, 2623722  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=46 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
 ... ...

When I want to plot a single line, I can plot it as

plot(SL1[[1]])

But if I want to plot all the lines together, R throws an error:

> plot(SL1)
Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' is a list, but does not have components 'x' and 'y'

I know I have to unlist, but it remains the same after I write:

SL1<-unlist(SL1)

Any solution??

Depend answered 2/8, 2013 at 18:8 Comment(1)
Wouldn't this just be lapply(SL1, plot), or perhaps lapply(SL1, function(x) plot(x, add=TRUE))? At the moment all you deserve are guesses since you have provided no test data.Ideography
G
6

You need to put them all into one SpatialLines object. To do this you need to extract the Lines objects from each SpatialLines item in your list, then you can extract the individual lines objects from this, then you can use this list to recombine them into a single SpatialLines object:

#  Get the Lines objects which contain multiple 'lines'
ll0 <- lapply( SL1 , function(x) `@`(x , "lines") )

#  Extract the individual 'lines'
ll1 <- lapply( unlist( ll0 ) , function(y) `@`(y,"Lines") )

#  Combine them into a single SpatialLines object
Sl <- SpatialLines( list( Lines( unlist( ll1 ) , ID = 1 ) ) )

S4 classes!

Glucosuria answered 2/8, 2013 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.