首页 > 解决方案 > 无法在 R 中读取 shp 文件

问题描述

我尝试使用以下代码在我的 Mac 上打开一个 shp 文件:

library(tidyverse)
library(sf)
library(rgeos)
sf_trees_raw <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-01-28/sf_trees.csv')
temp_shapefile <- tempfile()
download.file("https://www2.census.gov/geo/tiger/TIGER2017//ROADS/tl_2017_06075_roads.zip", temp_shapefile)
sf_roads <- unzip(temp_shapefile, "tl_2017_06075_roads.shp") %>%
  read_sf()

但我收到此错误消息:

Error: Cannot open "/Users/name/Documents/Playground/Trees_SF/tl_2017_06075_roads.shp"; The source could be corrupt or not supported. See `st_drivers()` for a list of supported formats.

我尝试了其他 shp 文件,并且收到相同的错误消息:

map <- read_sf("per_admbnda_adm1_2018.shp")
Error: Cannot open "/Users/name/Documents/Playground/Trees_SF/per_admbnda_adm1_2018.shp"; The source could be corrupt or not supported. See `st_drivers()` for a list of supported formats.

我尝试复制 shx 和 dbf 文件,但没有解决问题。

任何帮助将不胜感激。

标签: rsf

解决方案


尝试先解压缩整个下载文件,然后读取 shapefile 文件。虽然sf您只需要指向.shp文件,但所有其他文件(.cpg.prj.shx等)都需要解压缩并位于同一目录中。

temp_shapefile <- tempfile()
download.file("https://www2.census.gov/geo/tiger/TIGER2017//ROADS/tl_2017_06075_roads.zip", temp_shapefile)
unzip(temp_shapefile)

sf_roads <- read_sf('tl_2017_06075_roads.shp')

推荐阅读