How to clip WorldMap with polygon in R?

后端 未结 2 1738
渐次进展
渐次进展 2020-12-25 09:04

I have imported a world map dataset from www.GADM.org using the R package raster. I would like to clip it to a polygon I create to reduce the size of the map. I can retrieve

2条回答
  •  醉酒成梦
    2020-12-25 09:20

    How about a little intermediate step? I adopted the following code mainly from R-sig-Geo and I think it should do the trick. You'll need both 'maptools' and 'PBSmapping' packages, so make sure you've got them installed. Here's my code:

    # Required packages
    library(raster)
    library(maptools)
    library(PBSmapping)
    
    # Download world map
    WorldMap <- getData('countries')
    # Convert SpatialPolygons to class 'PolySet'
    WorldMap.ps <- SpatialPolygons2PolySet(WorldMap)
    # Clip 'PolySet' by given extent
    WorldMap.ps.clipped <- clipPolys(WorldMap.ps, xlim = c(-20, 40), ylim = c(30, 72))
    # Convert clipped 'PolySet' back to SpatialPolygons
    EuropeMap <- PolySet2SpatialPolygons(WorldMap.ps.clipped, close_polys=TRUE)
    

    I just tested it and it worked without any problems. It took some computation time to transform SpatialPolygons to PolySet, though.

    Cheers, Florian

提交回复
热议问题