2

I would like to expand on this function. As of now, the function downloads and unzips the shape file from the web. I would like to implement 'rgdal' to read the file into R.

library(rgdal)
dlshape=function(location) {
    temp=tempfile()
    download.file(location, temp)
    unzip(temp)
}

I found the following code on SO, but I was unsuccessful in adapting it. It appears that the function still looks at the first file unzipped rather than grep for a file ending with the .shp extension.

read.csv.zip <- function(zipfile, ...) {
# Create a name for the dir where we'll unzip
zipdir <- tempfile()
# Create the dir using that name
dir.create(zipdir)
# Unzip the file into the dir
unzip(zipfile, exdir=zipdir)
# Get a list of csv files in the dir
files <- list.files(zipdir)
files <- files[grep("\\.csv$", files)]
# Create a list of the imported csv files
csv.data <- sapply(files, function(f) {
    fp <- file.path(zipdir, f)
    return(read.csv(fp, ...))
})
return(csv.data)}

dlshape=function(shploc, shpfile) {
  temp=tempfile()
  download.file(shploc, temp)
  unzip(temp, exdir = temp)
  files<-list.files(temp)
  files <- files[grep("\\.shp$", files)]
  shp.data <- sapply(files, function(f) {
    fp <- file.path(zipdir, f)
    return(ReadOGR(fp, ...))
})
return(shp.data)}

Could someone please help me in figuring this out. I would gladly appreciate it.

EDIT: Included my adaptation for clarification on the "adapting" part.

Andre Silva
  • 4,782
  • 9
  • 52
  • 65
user2340706
  • 361
  • 2
  • 12
  • Is the shapefile in a nested folder after you unzip? If yes, turn on the recursive argument in list.files. – mengeln Sep 23 '13 at 20:36

1 Answers1

3

Try this.

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

x = dlshape(shploc="http://www.location.com/file_name.zip", "file_name")
yokota
  • 1,007
  • 12
  • 23
  • Hi there, with `rgdal` retiring in 2023, do you have any idea how to amend the `dlshape` function so that it words with `sf`? I keep getting errors and can't find a working solution. Thanks! – Fred-LM Feb 27 '23 at 18:24
  • Not sure if this is what you were looking for, but this is using package(sf) which is still deependant on rgdal for the time being iirc. `dlshape=function(shploc, shpfile) { temp=tempfile() download.file(shploc, temp) unzip(temp) fp <- sf::read_sf(shpfile) return(fp) } ` `x = dlshape(shploc="http://www.location.com/file_name.zip", "file_name")` – Trevor Mar 28 '23 at 18:16