6

I tried to open an shp file on my Mac, using this code:

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()

But I receive this error message:

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.

I tried other shp files, and I receive the same error message:

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.

I tried copying the shx and dbf files but it doesn't fix the problem.

Any help will be greatly appreciated.

nniloc
  • 4,128
  • 2
  • 11
  • 22
Alexis
  • 2,104
  • 2
  • 19
  • 40

1 Answers1

11

Try unzipping the whole download first, then reading the shapefile file. Although for sf you only need to point at the .shp file, all the other ones (.cpg, .prj, .shx, etc) need to be unzipped and in the same directory.

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')
nniloc
  • 4,128
  • 2
  • 11
  • 22
  • 1
    Hello @cnicol, thank you very much! I can't understand why the piping couldn't work but your proposed solution works fine!. The only thing that I don't understand is why if I copied all the files you mentioned in the working directory it couldn't read the shp file. Any – Alexis Apr 18 '20 at 01:06
  • 2
    I think if you specify a file in `zip` then it will only unzip the one file, so when you pipe to `read_sf` it can only find the one file. [Here](https://stackoverflow.com/a/59741450/12400385) is a similar answer, but they send the unzipped files into a new folder – nniloc Apr 18 '20 at 03:52
  • Thank you, now I understand why it couldn’t work! It was just reading one file. – Alexis Apr 20 '20 at 01:52
  • What about the last section of code where you were trying to open a shapefile that wasn't a zip file? I'm having the same problem on a mac, trying to open a shapefile that has all necessary files together. – canderson156 Feb 04 '21 at 16:12