Yansisi
Yansisi

Reputation: 49

subset shape file data

I have a shapefile contain 500 MSAs (city or towns), I would like to subset some of the MSAs, but my R code just not work. I will be appreciated could help me or give me some suggestion.

Here is the link to shapefile shape file

Here is my R code:

# 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") 

The ggplot is NE state arould 500 MSAS plot. I want to focus on these 7 counties: washington,douglas,sarpy,cass,saunders,lancaster,seward.

But the shapefile didn't have county, so I try to subset by NAME.

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

But it shows Error.

Error in [.data.frame(x@data, i, j, ..., drop = FALSE) : undefined columns selected

Upvotes: 3

Views: 1592

Answers (2)

Tung
Tung

Reputation: 28331

You need to do a little bit more to get both NAME, lat, long in the same data frame for plotting

    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

Upvotes: 2

spinodal
spinodal

Reputation: 680

You didn't put the names in a vector.

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

Upvotes: 0

Related Questions