[R-sig-Geo] interoperating SpatialLinesDataFrame, SpatialPolygonsDataFrame

Tom Roche Tom_Roche at pobox.com
Mon Feb 25 23:18:49 CET 2013


How to cast SpatialPolygonsDataFrame (SPDF) to SpatialLinesDataFrame
(SLDF), or vice versa? Alternatively, how best to write a function to
use either an SPDF or an SLDF as a map overlay in levelplot(...)?
Why I ask:

https://bitbucket.org/tlroche/clm_cn_global_to_aqmeii-na

regrids a dataset from global/unprojected to LCC over a superset of
CONUS ("AQMEII-NA"). I currently have code that gets a projected map
of the CONUS state boundaries with

+ state.map <- maps::map(
+   database="state", projection="lambert", par=c(33,45), plot=FALSE)

tweaks the coordinates, and converts the map to an SLDF

> state.map.IOAPI.shp <-
>   maptools::map2SpatialLines(state.map.IOAPI, proj4string=out.crs)

I then pass the SLDF to a function (which I wrote because I'll be
repeating this task with different datasets) to overlay that map onto
plots of the layers of a RasterBrick:

> plot(rasterVis::levelplot(brick,
>   margin=FALSE,
>   layout=c(1,length(names(brick)))
> ) +
>   latticeExtra::layer(
>     sp::sp.lines(map.shp, lwd=0.8, col='darkgray')))

I want to include Canada and Mexico in my map overlay, since the
horizontal domain includes large portions. I can do

> library(maptools)
> data(wrld_simpl) # from maptools
> map.noram.shp.unproj <- 
>   wrld_simpl[wrld_simpl$ISO3 %in% c('CAN', 'MEX', 'USA'),]
> map.noram.shp.proj <-
>   rgdal::spTransform(map.noram.shp.unproj, CRS=out.crs)

But the latter is an SPDF, for which my function above throws an error
(since sp::sp.lines wants a SLDF). I'm guessing I could change the code
to use sp::sp.polygons as needed (with some sort of `if` or `case`
checking the class of the map), but I'd much prefer to just convert the
SPDF to an SLDF (since I'm not using the polygon's fill or other
attributes). How best to do that? Or is the way to do this Something
Completely Different?

Apologies if this is a FAQ, but I'm not seeing the answer in doc
(sp.pdf or intro_sp.pdf) or via googling.

TIA, Tom Roche <Tom_Roche at pobox.com>



More information about the R-sig-Geo mailing list