2013-09-23 33 views
1

我想展开这个函数。截至目前,该功能从网上下载并解压缩形状文件。我想实现“rgdal”将文件读入R.在R下载并阅读shapefile函数

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

我发现下面的代码对SO,但我适应它不成功。对于以.shp扩展名结尾的文件,该函数看起来仍然是解压缩的第一个文件,而不是grep。

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

有人可以帮我解决这个问题。我很乐意欣赏它。

编辑:包括我的适应澄清“适应”部分。

+0

解压缩后,shapefile是否位于嵌套文件夹中?如果是,请打开list.files中的递归参数。 – mengeln

+0

没有嵌套的文件夹。 – user2340706

回答

1

试试这个。

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

谢谢,这是我正在寻找。 – user2340706