简体   繁体   中英

Clipping surface polygon by a rather nasty large Spatial polygon data frame

I have come across a tricky issue.

I am trying to perfom a simple polygon clip using sp package, either using the fuction st_difference(st_union(x),st_union(y)) (or a variant there of) or st_intersection function, whichever works best.

While this is easy with two surface polygons, I need to clip it to a horrible large downloaded Large SpatialPolygonsDataFrame, its just a shapefile for the UK, downloaded from: https://gadm.org/download_country_v3.html

The shapefiles are as as follows (plotted in leaflet ): 在此处输入图片说明

    > str(uk)
    Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
      ..@ data       :'data.frame': 1 obs. of  70 variables:
      .. ..$ ID_0      : Factor w/ 1 level "242": 1
      .. ..$ ISO       : Factor w/ 1 level "GBR": 1
      .. ..$ NAME_0    : Factor w/ 1 level "United Kingdom": 1
    # .....etc.
    #
    > str(box)
    sfc_POLYGON of length 1; first list element: List of 1
     $ : num [1:5, 1:2] -7.237 0.126 0.126 -7.237 -7.237 ...
     - attr(*, "class")= chr [1:3] "XY" "POLYGON" "sfg"

I want to clip the box (blue) to the uk , the reason for this is it takes too long to render the shapefile in of the UK (and france for that matter) in leaflet.

This will probably do?

sf::st_intersection(UK, box)

Complete code

library(sf)

UK <- readRDS("./gadm36_GBR_0_sf.rds")

#create box since it was not provided in question
box <- c("POLYGON((-7.237 48,0 48,0 52,-7.237 52, -7.237 48))") %>% 
  st_as_sfc(crs = "+proj=longlat +datum=WGS84")

mapview::mapview(list(UK,box))

在此处输入图片说明

mapview::mapview( st_intersection(UK, box) )

在此处输入图片说明

update

If you want to cut the box with the shapefile of the UK, use st_difference()

mapview::mapview( st_difference (box, UK) )

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM