r - 在没有安装 rgdal 的情况下在 R 中解压缩和读取形状文件
问题描述
我想在不依赖 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()
from utils 和read_sf()
from 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)
推荐阅读
- javascript - fetch .then 回调函数中的隐式响应
- reporting-services - 需要一个智能解决方案来获取 SSRS 报告中使用的所有属性列表
- python - 如何在 txt 文件中正则表达式此 tetxt?
- arrays - 为什么 printf 打印一个字符数组的一个额外字节,但前提是最后一个元素不是空字符 \0?
- html - 为什么徽标图像未在通过 nodemailer 发送的 html 中的电子邮件模板中呈现
- c++ - 使用路径名前缀 \\?\ 调用 CreateFile 失败(但目录结构存在
- multithreading - Julia 没有使用所有可用的 CPU 线程
- java - 杰克逊解析器可以用来解析 JSON5 吗?
- reactjs - 带有时间间隔的 useEffect 每次运行两次
- json - Rocket - 使用 Rocket 和 okapi 处理无类型的 json 正文