gpt4 book ai didi

r - 子集形状文件数据

转载 作者:行者123 更新时间:2023-12-04 16:06:32 26 4
gpt4 key购买 nike

我有一个包含 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 state arould 500 MSAS plot。我想重点关注这 7 个县:华盛顿、道格拉斯、萨尔皮、卡斯、桑德斯、兰开斯特、苏厄德。

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

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

但是显示错误。

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

最佳答案

您需要做更多的工作才能同时获得 NAME , lat , long在同一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

关于r - 子集形状文件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com