从多个文件夹中读取 shapefile

Read shapefiles from many folders

我的 shapefile 分布在许多文件夹中,我想将它们拉出来并 运行 一个脚本来以相同的方式处理每个文件。所有 .shp 文件都具有相同的名称,我需要文件夹名称作为 id(尚未尝试该部分)。我卡在了第一步,但我觉得我已经接近了。

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

抱歉,我没有这方面的代表,如果我能在这里得到一些牵引力,也许我明天可以建一个。

我觉得你很接近。我认为您只需要三个修复 1) 使用 paste0() 函数在“dsn”参数中组合文件夹名称和 shapefile 名称,2) 在您的 all_files() 中添加一个 return() 调用函数和 3) 从 map() 切换到 do.call()lapply()。尝试像这样调整您的代码:

# 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

如果这不起作用,您可以考虑使用 sf::read_st() 函数

读取 shapefile