在R中不安装rgdal包如何解压和读取shape文件

8
我希望在R中无需依赖rgdal解压并读取来自Web的shape文件。我发现fastshp包的read.shp函数可以在环境中没有安装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()中我使用的文件夹名称而不是.shp文件名有关(对于readOGR可以工作,但对于read.shp不行)。非常感谢您的任何帮助。
1个回答

17

您可以使用来自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)

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