【问题标题】:subset shape file data子集形状文件数据
【发布时间】:2018-01-29 17:45:16
【问题描述】:

我有一个包含 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) 中的错误: 选择了未定义的列

【问题讨论】:

    标签: r subset shapefile


    【解决方案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") 
    

    【讨论】:

    • 当然,我想这样做,但我怎么能接受你的回答,我在哪里可以这样做?抱歉,我是这个网站的新手。
    【解决方案2】:

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

    s &lt;-subset(msa, NAME==c("Alvo","Avoca","Cedar Creek","Eagle","Elmwood")) 应该可以工作

    【讨论】:

    • 谢谢。有用。但数据也不见了。{msa
    • subset(msa, NAME %in% c("Alvo","Avoca","Cedar Creek","Eagle","Elmwood")) 或 msa[msa$NAME %in% c ("Alvo","Avoca","Cedar Creek","Eagle","Elmwood"),]
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2017-08-25
    相关资源
    最近更新 更多