如何在R中绘制形状文件之前对其进行过滤

时间:2018-05-01 02:42:01

标签: r filtering shapefile

尝试过滤形状文件以简化绘图

我有从英国政府下载的形状文件:

http://geoportal.statistics.gov.uk/datasets/7ff28788e1e640de8150fb8f35703f6e_1/data?geometry=-76.678%2C45.365%2C69.572%2C63.013&orderBy=lad16cd&orderByAsc=false&where=%20(UPPER(lad16cd)%20like%20%27%25E0800000%25%27%20OR%20UPPER(lad16cd)%20like%20%27%25E08000010%25%27)%20

基于此:https://www.r-bloggers.com/r-and-gis-working-with-shapefiles/

我写了但不知道要过滤:

setwd("~/Documents/filename")
getwd() #  --double confirm real data directory
#install.packages("maptools")
library(maptools)
crswgs84=CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
ukmap=readShapePoly("filename.shp",proj4string=crswgs84,verbose=TRUE)

class(ukmap)
str(ukmap@data)
str(ukmap@polygons[[1]])
ukmap@bbox
# <-- need to do some filterig
plot(ukmap) # as this will take too long and not want to plot whole UK

例如我只想要“E06000001”到“E06000020”。

(文件名为“Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK”,不知道如何将其包含在程序编码报价中)

1 个答案:

答案 0 :(得分:2)

您可以考虑使用sf包来读取shapefile并绘制数据。过滤sf对象与过滤数据框相同。

library(sf)

# Read the sahpefile
ukmap <- st_read("Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK.shp")

# Subset the sf object
ukmap_sub <- ukmap[ukmap$lad16cd %in% c("E06000001", "E06000020"), ]

# Plot the boundary of ukmap_sub
plot(st_geometry(ukmap_sub))

enter image description here

如果您希望使用SpatialPolygonsDataFrame,我们可以使用包中的readOGR功能。之后,我们可以像常规数据框一样对SpatialPolygonsDataFrame进行子集化。

library(maptools)
library(rgdal)

ukmap <- readOGR(dsn = getwd(), layer = "Local_Authority_Districts_December_2016_Full_Extent_Boundaries_in_the_UK")

ukmap_sub <- ukmap[ukmap$lad16cd %in% c("E06000001", "E06000020"), ]

plot(ukmap_sub)

enter image description here