在没有安装 rgdal 的情况下在 R 中解压缩和读取形状文件

Unzipping and reading shape file in R without rgdal installed

我想在不依赖 rgdal 的情况下在 R 中解压缩并读取来自网络的形状文件。我发现 fastshp 包的 read.shp 函数显然可以在没有在环境中安装 rgdal 的情况下完成此操作,但是,我在实现时遇到了麻烦。

我想要一个可以解压缩然后读取形状文件的函数,类似于此 SO post 中找到的内容,但 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() 中,我向它提供了文件夹名称而不是 .shp 名称(对于 readOGR 有效,但对于 read.shp).非常感谢任何帮助。

您可以使用 utils 中的 unzip() 和 sf 中的 read_sf() 来解压缩,然后加载您的 shapefile。这是一个工作示例:

# Create temp files
temp <- tempfile()
temp2 <- tempfile()

# Download the zip file and save to 'temp' 
URL <- "https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip"
download.file(URL, temp)

# Unzip the contents of the temp and save unzipped content in 'temp2'
unzip(zipfile = temp, exdir = temp2)

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