I have shapefiles spread over many folders and I'd like to pull them out and run a script to process each one in the same way. All the .shp files have the same name and I need to folder name to come along as an id (haven't attempted that part yet). I am stuck on the first step, but I feel like I am close.
# Read folder names to get list of folders
folders <- list.dirs(path = "./locs", full.names = TRUE, recursive = TRUE)
# Make function that reads inside a folder same way for all files
all_files <- function(folder) {
readOGR(dsn = folder, layer = "SAMENAME.shp", verbose = FALSE)
}
# Map the function to each folder listed in "folders".
try <- map(folders, all_files)
Sorry I don't have a reprex for this, maybe I can build one tomorrow if I can get some traction here.
I think you are pretty close. I think you just need three fixes 1) use a paste0()
function to combine the folder name and the shapefile name in the "dsn" argument, 2) add a return()
call in your all_files()
function and 3) switch from map()
to either do.call()
or lapply()
. Try tweaking your code like this:
# Read folder names to get list of folders
folders <- list.dirs(path = "./locs", full.names = TRUE, recursive = TRUE)
# Make function that reads inside a folder same way for all files
all_files <- function(folder) {
out<-readOGR(dsn = paste0(folder, "SAMENAME.shp", sep+"/), layer = "SAMENAME.shp", verbose = FALSE)
return(out)
}
# Map the function to each folder listed in "folders".
try <- lapply(folders, all_files) #lapply() approach
try2 <- do.call(all_files, folders) #do.call() approach
If that doesn't work, you could consider reading in the shapefiles using the sf::read_st()
function