子集形状文件数据

时间:2018-01-29 17:45:17

标签: r subset shapefile

我有一个包含500个MSA(城市或城镇)的shapefile,我想将一些MSA分配,但我的R代码不起作用。我将不胜感激,可以帮助我或给我一些建议。

这是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状态的500 MSAS图。我想专注于这7个县:华盛顿,道格拉斯,萨里,卡斯,桑德斯,兰开斯特,塞弗德。

但是shapefile没有县,所以我尝试按NAME进行分组。

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

但它显示错误。

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

2 个答案:

答案 0 :(得分:1)

您需要多做一点才能同时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") 

enter image description here

答案 1 :(得分:0)

你没有把名字放在矢量中。

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