简体   繁体   English

在R中使用shapefile显示区域的子集

[英]display a subset of regions using a shapefile in R

I have a shapefile of the UK: https://geoportal.statistics.gov.uk/Docs/Boundaries/Local_authority_district_(GB)_2014_Boundaries_(Generalised_Clipped).zip 我有一个英国的shapefile: https ://geoportal.statistics.gov.uk/Docs/Boundaries/Local_authority_district_(GB)_2014_Boundaries_(Generalised_Clipped).zip

I've read the shapefile into a variable, UK 我已经将shapefile读入变量,英国

>UK <- readOGR(dsn = "....."
>England <- UK

I'd like to only display English Local Authority regions. 我只想显示英语地方当局地区。 They are specified in the LAD_DEC_2014_GB_BGC.dbf where LAD14CD starts with "E" 它们在LAD_DEC_2014_GB_BGC.dbf中指定,其中LAD14CD以“ E”开头

>UK@data

      LAD14CD                      LAD14NM                 LAD14NMW

0   E06000001                   Hartlepool                     <NA>
1   E06000002                Middlesbrough                     <NA>
2   E06000003         Redcar and Cleveland                     <NA>
371 W06000015                      Cardiff                 Caerdydd

>#filter UK@data and replace England@data with only English regions
>England@data <- UK@data$LAD14CD[c(grep("^E", UK$LAD14CD))]

>plot(England)

But the grep command appears to change the shapefile into a factor, meaning the plot looks like this: 但是grep命令似乎将shapefile更改为一个因子,这意味着该图看起来像这样: 在此处输入图片说明

With this command: 使用此命令:

England <- UK@data$LAD14CD[c(grep("^E", UK$LAD14CD))]

...you are subsetting just one column from the data slot, not the whole shapefile and assigning that to England . ...您只在数据槽中分配一列,而不是整个shapefile并将其分配给England

This ought to do the job: 这应该做的工作:

England <- UK[grep("^E", UK@data$LAD14CD),]

Note, you need the trailing comma in there! 请注意,您需要在其中加上逗号! Also you don't need to wrap the grep statement in c() , but that doesn't hurt it's just unnecessary. 另外,您不需要将grep语句包装在c() ,但这并没有什么害处,这只是不必要的。

I ended up using dplyr and grepl instead to make things simpler: 我最终使用dplyrgrepl简化了事情:

library('rgdal')
library('dplyr')

UK <- readOGR(dsn="LAD_DEC_2014_GB_BGC.shp", layer="LAD_DEC_2014_GB_BGC") %>%
  subset(grepl("^E", LAD14CD))
plot(UK)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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