Распаковка и чтение файла формы в R без установленного rgdal - PullRequest
0 голосов
/ 14 января 2020

Я хотел бы распаковать и прочитать файл формы из Интернета в R, не полагаясь на rgdal. Я обнаружил функцию read.shp пакета fastshp, которая, по-видимому, может выполнить это sh без rgdal, установленного в среде, однако у меня возникли проблемы с реализацией.

Мне нужна функция, которая может разархивируйте, а затем прочитайте файл формы, похожий на то, что находится в этом посте SO , но для функции read.shp. Я пробовал следующее, но безрезультатно:

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

shp_object<-dlshape('https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip', 'polygon')
 Error in read.shp(".", format) : unused argument (format) 

Я также пробовал следующее:

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

 shp_object<-dlshape('https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip')

Error in file(shp.name, "rb") : cannot open the connection
In addition: Warning messages:
1: In file(shp.name, "rb") : 'raw = FALSE' but '.' is not a regular file
2: In file(shp.name, "rb") :
 Show Traceback
 Rerun with Debug
 Error in file(shp.name, "rb") : cannot open the connection

Я подозреваю, что это связано с тем, что в функции read.shp() I Я передаю ему имя папки, а не имя .shp (для readOGR, которая работает, но не для read.shp). Любая помощь очень ценится.

1 Ответ

2 голосов
/ 14 января 2020

Вы можете использовать unzip() из утилиты и read_sf() из sf, чтобы распаковать и загрузить шейп-файл. Вот рабочий пример:

#create a couple temp files
temp <- tempfile()
temp2 <- tempfile()
#download the zip folder from the internet save to 'temp' 
download.file("https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip",temp)
#unzip the contents in 'temp' and save unzipped content in 'temp2'
unzip(zipfile = temp, exdir = temp2)
#finds the filepath of the shapefile (.shp) file in the temp2 unzip folder
#the $ at the end of ".shp$" ensures you are not also finding files such as .shp.xml 
your_SHP_file<-list.files(temp2, pattern = ".shp$",full.names=TRUE)

#read the shapefile. Alternatively make an assignment, such as f<-sf::read_sf(your_SHP_file)
sf::read_sf(your_SHP_file)
...