如何在R中直接从Github仓库导入和读取一个shapefile?

n6lpvg4x  于 2023-02-06  发布在  Git
关注(0)|答案(2)|浏览(152)

我喜欢在Github存储库中存储一些东西,以便在R中的任何地方访问和读取,比如CSV文件,可以从存储库链接中读取,而无需下载到我计算机上的目录中。
但我想对shapefile文件做同样的事情,它是gospatial文件,分为4个部分或扩展名:*.shp*.shx*.prj*dbf,每个都有其功能。*.shp扩展名由空间支持的软件读取。
我试着从github存储库加载一个shapefile,但是我不能。

library(rgdal) 
shapefile <- readOGR("http://wesleysc352.github.io/seg_s3_r3_m10_fix_estat_amost_val.shp")
ruarlubt

ruarlubt1#

您可以使用GDAL虚拟文件系统与sf::st_read(),一个通过HTTP和FTP阅读文件是/vsicurl/,显然它的能力足以找出哪些额外的文件,它应该拉,使Shapefile的工作:

library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
shp <- st_read("/vsicurl/http://wesleysc352.github.io/seg_s3_r3_m10_fix_estat_amost_val.shp")
#> Reading layer `seg_s3_r3_m10_fix_estat_amost_val' from data source 
#>   `/vsicurl/http://wesleysc352.github.io/seg_s3_r3_m10_fix_estat_amost_val.shp' 
#>   using driver `ESRI Shapefile'
#> Simple feature collection with 2308 features and 2 fields
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 752896 ymin: 7734010 xmax: 761686 ymax: 7744258
#> Projected CRS: WGS 84 / UTM zone 21S

head(shp)
#> Simple feature collection with 6 features and 2 fields
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 753792 ymin: 7744136 xmax: 753880 ymax: 7744188
#> Projected CRS: WGS 84 / UTM zone 21S
#>     id amostra                       geometry
#> 1 1996       4 POLYGON ((753854 7744188, 7...
#> 2 2206       4 POLYGON ((753792 7744176, 7...
#> 3 2254       4 POLYGON ((753872 7744172, 7...
#> 4 2460       4 POLYGON ((753870 7744170, 7...
#> 5 2707       4 POLYGON ((753840 7744158, 7...
#> 6 2814       4 POLYGON ((753838 7744150, 7...

创建于2023年2月5日,使用reprex v2.0.2
虽然根据您的用例,GeoJSON和/或GeoPackage可能更适合版本控制和远程访问,但sf(与大多数其他地理空间库和工具一样)可以读写这两者。

wmvff8tz

wmvff8tz2#

我不知道是否有更简单的方法,但这里有一个函数,下载所有的文件到本地计算机,然后读取它们。

library(stringr)
library(sf)

load_shp <- function(shape_link, dest_dir="shape_files"){

  #check for dest dir, create it if it doesn't exist
  if(!dir.exists(dest_dir)){
  
    dir.create(dest_dir) 
    
  }
  
#remove file extension (everything after last period)  
shape_link <- str_remove(url, "\\.[^\\.]+$")

# Extract file name (everything after last /)
file_name <- shape_link %>% str_extract("/[^/]+$.*") %>% str_remove("/")

# define extensions
ext <- c(".shp", ".shx", ".prj", ".dbf")

#create list of urls
urls <- paste0(shape_link, ext)

#create a list of download files
downloaded_files <- paste0(file_name,ext)

for (i in seq_along(urls)) {

download.file(urls[i],downloaded_files[i])
  
}

shape <- st_read(downloaded_files[1])

shape
}

shape <- load_shp("http://wesleysc352.github.io/seg_s3_r3_m10_fix_estat_amost_val.shp")

相关问题