在 readOGR 批量读取中包含文件名

Include filenames in readOGR batch reading

我正在使用 shapefile,其中位置 ID 数据仅在文件夹名称中可用。我编写了以下代码来批量读取文件,但我正在努力解决如何在列中也包含位置 ID 文件夹名称的问题。

folders <- list.dirs(path = "/home/username/foldername/location_id", 
full.names = TRUE, recursive = TRUE)

all_files <- function(folder) {
  out<-readOGR(dsn = paste0(folder), layer = "SAMENAME", verbose = TRUE)
    return(out)
}

my_shapefiles <- purrr::map(folders, safely(all_files))

两种方法:

folder <- "/home/username/foldername/folder2"

basename(folder)
#> [1] "folder2"
gsub(".*\/(.*)$", "\1", folder)
#> [1] "folder2"

因此,您可以这样修改函数:

all_files <- function(folder) {
  out <- readOGR(dsn = paste0(folder), layer = "SAMENAME", verbose = TRUE)
  out$id <- basename(folder)
    return(out)
}

由 reprex 包 (v2.0.1) 创建于 2021-10-18