2013-09-23 66 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