You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

readOGR批量读取shapefile时如何将文件夹名作为location_id列写入

解决方案

你只需要在读取空间数据的函数里新增一步提取文件夹名、写入属性列的操作即可,具体修改如下:

步骤1:修改读取函数,自动新增location_id列

你可以用basename()函数直接提取路径最后一级的文件夹名作为location_id,直接写入SpatialDataFrame的属性表:

library(rgdal)
library(purrr)

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

all_files <- function(folder) {
  # 读取shp文件
  out <- readOGR(dsn = folder, layer = "SAMENAME", verbose = TRUE)
  # 新增location_id列,取值为当前文件所属的上级文件夹名
  out$location_id <- basename(folder)
  return(out)
}

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

步骤2:提取读取成功的结果(可选)

因为你用了safely()包裹函数,最终返回的列表每个元素都包含result(读取成功的空间数据)和error(读取失败的报错信息),你可以用下面的代码提取所有读取成功的空间对象:

# 筛选读取成功的结果索引
success_idx <- map_lgl(my_shapefiles, ~is.null(.x$error))
success_shapefiles <- map(my_shapefiles[success_idx], ~.x$result)

# 如果需要把所有空间数据合并为一个Spatial*DataFrame,可直接用rbind拼接
if (length(success_shapefiles) > 0) {
  combined_shape <- do.call(rbind, success_shapefiles)
}

注意事项

  • 如果你的路径下存在没有对应SAMENAME.shp的文件夹,safely()会自动捕获报错不会中断运行,你可以通过map(my_shapefiles, ~.x$error)查看所有读取失败的原因
  • 如果后续你切换用sf包读取shp,新增列的逻辑完全通用,只需要把readOGR换成st_read()即可

内容的提问来源于stack exchange,提问作者Nazer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 21:27:01