我想回答一些问题,偶然发现了这个问题:
Read in all shapefiles in a directory in R
如果措辞更恰当,我发现这个问题会产生更大的影响。
我认为用户打算查询从特定目录批量加载shapefile到R的方法。
我在下面提供我的解决方案。我欢迎任何有关如何通过以下答案加强它的建议。
答案 0 :(得分:1)
#--download shapefiles from here:
#--https://www.census.gov/geo/maps-data/data/cbf/cbf_cds.html
wd <- "/My Shapefiles"
setwd(wd)
#--store shapefile names as a list
shp_files <- list.files(wd, pattern = "\\.shp$")
#--inspect list
print(shp_files)
####################################
# Batch shapefile loading function #
####################################
rgdal_batch_shp <- function(shp_list) {
layer_name <- as.character(gsub(".shp","",shp_list))
shp_spdf <-readOGR(dsn = wd, stringsAsFactors = FALSE, verbose = TRUE,
useC = TRUE, dropNULLGeometries = TRUE, addCommentsToPolygons = TRUE,
layer = layer_name, require_geomType = NULL,
p4s = NULL, encoding = 'ESRI Shapefile')
}
#########################################
# Pass batch function to shapefile list #
#########################################
library(rgdal) #--for readOGR function
#--Use lapply to pass rgdal_batch_shp function to files list.
batch_shp_list <- lapply(shp_files, rgdal_batch_shp)
#--Extract each element in list into its own object
for (i in seq(batch_shp_list))
assign(paste("test_shp", i, sep = ""), batch_shp_list[[i]])