gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:35:14 24 4
gpt4 key购买 nike

我想在不依赖 rgdal 的情况下从 R 中的网络解压缩并读取形状文件。我找到了 read.shp fastshp的功能显然可以在没有在环境中安装 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 )。非常感谢任何帮助。

最佳答案

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

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

关于r - 在没有安装 rgdal 的情况下解压缩和读取 R 中的形状文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59740419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com