Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unzipping and reading shape file in R without rgdal installed

I would like to unzip and read in a shape file from the web in R without relying on rgdal. I found the read.shp function of the fastshp package that can apparently accomplish this without rgdal installed in the environment, however, I'm having trouble implementing.

I would like a function that can unzip and then read in the shape file akin to what's found in this SO post but for the read.shp function. I tried the following but to no avail:

dlshape=function(shploc, format) {
  temp=tempfile()
  download.file(shploc, temp)
  unzip(temp)
  shp.data <- sapply(".", function(f) {
    f <- file.path(temp, f)
    return(read.shp(".", format))
  })
}

shp_object<-dlshape('https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip', 'polygon')
 Error in read.shp(".", format) : unused argument (format) 

I also tried the following:

  dlshape=function(shploc) {
      temp=tempfile()
      download.file(shploc, temp)
      unzip(temp)
      shp.data <- sapply(".", function(f) {
        f <- file.path(temp, f)
        return(read.shp("."))
      })
    }

 shp_object<-dlshape('https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip')

Error in file(shp.name, "rb") : cannot open the connection
In addition: Warning messages:
1: In file(shp.name, "rb") : 'raw = FALSE' but '.' is not a regular file
2: In file(shp.name, "rb") :
 Show Traceback
 Rerun with Debug
 Error in file(shp.name, "rb") : cannot open the connection

I suspect it has to do with the fact that in the function read.shp() I'm feeding it the folder name and not the .shp name (for readOGR that works but not for read.shp). Any assistance is much appreciated.

like image 539
Cyrus Mohammadian Avatar asked Dec 22 '22 19:12

Cyrus Mohammadian


1 Answers

You can use unzip() from utils and read_sf() from sf to unzip and then load your shapefile. Here is a working example:

# Create temp files
temp <- tempfile()
temp2 <- tempfile()

# Download the zip file and save to 'temp' 
URL <- "https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip"
download.file(URL, temp)

# Unzip the contents of the temp and save unzipped content in 'temp2'
unzip(zipfile = temp, exdir = temp2)

# Read the shapefile. Alternatively make an assignment, such as f<-sf::read_sf(your_SHP_file)
sf::read_sf(temp2)
like image 59
SEAnalyst Avatar answered Feb 23 '23 00:02

SEAnalyst