Download and read shapefile function in R

此生再无相见时 提交于 2020-02-29 05:10:27

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/18967722/download-and-read-shapefile-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!