子集形状文件数据

subset shape file data

我有一个包含 500 个 MSA(城市或城镇)的 shapefile,我想对一些 MSA 进行子集化,但我的 R 代码不起作用。如果能帮助我或给我一些建议,我将不胜感激。

这里是 link 到 shapefile shape file

这是我的 R 代码:

# generating plot of bangladesh district map
# the shape file is downloaded from the link
# https://catalog.data.gov/dataset/tiger-line-shapefile-2014-state-nebraska-current-place-state-based-shapefiles/resource/f6c6e766-d785-4da3-9141-7c0ea144d0bf

msa <- readOGR(dsn = "tl_2014_31_place.shp", layer="tl_2014_31_place")
msa <- spTransform(msa, CRS("+proj=longlat +datum=WGS84"))
msa <- fortify(msa) # converts shape file into ggplot-able data frame

ggplot(msa, aes(x=long, y=lat, group=group)) + 
  geom_polygon(fill="grey65", colour = alpha("white", 1/2), size = 0.2) + theme_bw() + 
  theme(legend.position = "none", text = element_blank(), line = element_blank()) + 
  coord_map("polyconic") 

ggplot 是 NE state arould 500 MSAS 图。我想重点关注这 7 个县:华盛顿、道格拉斯、萨尔皮、卡斯、桑德斯、兰开斯特、苏厄德。

但是 shapefile 没有县,所以我尝试按 NAME 进行子集化。

> s <-subset(msa, NAME=="Alvo","Avoca","Cedar Creek","Eagle","Elmwood")

但是显示错误。

[.data.frame(x@data, i, j, ..., drop = FALSE) 中的错误: 选择了未定义的列

您没有将名称放入向量中。

s <-subset(msa, NAME==c("Alvo","Avoca","Cedar Creek","Eagle","Elmwood")) 应该有效

您需要做更多的工作才能让 NAMElatlong 在同一个 data frame 中进行绘图

    library(rgdal)
    library(tidyverse)

    msa <- readOGR(dsn = paste0("tl_2014_31_place.shp"), layer="tl_2014_31_place")
    msa <- spTransform(msa, CRS("+proj=longlat +datum=WGS84"))
    msa@data$id = rownames(msa@data)
    msa.points = fortify(msa, region = "id")
    msa.df = merge(msa.points, msa@data, by = "id")

    selectedCounties <- c("Alvo", "Avoca", "Cedar Creek", "Eagle", "Elmwood")

    df <- msa.df %>% 
      filter(NAME %in% selectedCounties )

    ggplot(df, aes(x=long, y=lat, group=group)) + 
      geom_polygon(fill="grey65", colour = alpha("white", 1/2), size = 0.2) + theme_bw() + 
      theme(legend.position = "none", text = element_blank(), line = element_blank()) + 
      coord_map("polyconic")