在R中下载和读取shapefile函数

3

我希望你能扩展这个函数。目前,该函数从网上下载并解压缩形状文件。我想实现“rgdal”将文件读入R。

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

我在SO上找到了以下代码,但我没有成功地进行调整。看起来函数仍然只查看第一个解压缩的文件而不是grep以.shp扩展名结尾的文件。
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)}

请问有人能帮我弄清楚这个问题吗?非常感激。

编辑:为了更好地解释“适应”部分,我包含了我的改编内容。


解压后的shapefile是否位于嵌套文件夹中?如果是的话,请在list.files中打开递归参数。 - undefined
1个回答

4

试试这个。

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

嗨,由于 rgdal 将于2023年退役,你有没有想过如何修改 dlshape 函数以使其与 sf 兼容?我一直遇到错误,找不到可行的解决方案。谢谢! - undefined
不确定这是否符合您的要求,但目前还依赖于rgdal的package(sf)被使用在这里。 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") - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接