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

R语言中匹配数据框AnimalID与RasterLayer并执行栅格计算

解决方案

步骤1:提取栅格对应的AnimalID并命名列表

首先从栅格文件名中提取与数据框匹配的AnimalID,然后给栅格列表命名,方便后续匹配:

library(raster)

# 提取文件名并解析AnimalID(根据你的文件名格式调整正则)
raster_filenames <- basename(rasterlist)
# 从"702783_9088PR_PR.asc"中提取"702783_9088"
animal_ids <- sub("^(\\d+_\\d+).*\\.asc$", "\\1", raster_filenames)

# 给栅格列表命名为对应的AnimalID
names(allrasters.list) <- animal_ids

如果你的栅格@name属性已经是正确的AnimalID,可直接用以下代码命名列表:

names(allrasters.list) <- sapply(allrasters.list, function(x) x@name)

步骤2:匹配数据框并执行栅格缩放

先确保数据框的AnimalID为字符型,然后筛选出有对应栅格的记录,再对栅格值乘以对应位置数量:

# 转换AnimalID为字符型(避免因子类型匹配错误)
df$AnimalID <- as.character(df$AnimalID)

# 筛选数据框中存在对应栅格的行
matched_df <- df[df$AnimalID %in% names(allrasters.list), ]

# 批量处理栅格
scaled_rasters <- list()
for (i in seq(nrow(matched_df))) {
  id <- matched_df$AnimalID[i]
  count <- matched_df$`#Locations`[i]
  # 获取对应栅格并执行乘法
  scaled_raster <- allrasters.list[[id]] * count
  # 给结果栅格命名
  names(scaled_raster) <- paste0(id, "_scaled")
  scaled_rasters[[id]] <- scaled_raster
}

步骤3:保存处理后的栅格

创建输出文件夹并批量保存结果:

# 创建输出目录(不存在则新建)
if (!dir.exists("scaled_rasters_output")) {
  dir.create("scaled_rasters_output")
}

# 遍历保存每个缩放后的栅格
for (id in names(scaled_rasters)) {
  writeRaster(
    scaled_rasters[[id]],
    filename = file.path("scaled_rasters_output", paste0(id, "_scaled.asc")),
    format = "AAIGrid",
    overwrite = TRUE
  )
}

替代方案:用terra包高效处理

如果数据量较大,推荐使用terra包(比raster包更高效):

library(terra)

# 读取栅格为SpatRaster对象
allrasters.list <- lapply(rasterlist, rast)
# 命名列表(同步骤1)
names(allrasters.list) <- sub("^(\\d+_\\d+).*\\.asc$", "\\1", basename(rasterlist))

# 匹配并缩放
scaled_rasters <- list()
for (i in seq(nrow(matched_df))) {
  id <- matched_df$AnimalID[i]
  count <- matched_df$`#Locations`[i]
  scaled_raster <- allrasters.list[[id]] * count
  names(scaled_raster) <- paste0(id, "_scaled")
  scaled_rasters[[id]] <- scaled_raster
}

# 保存结果
dir.create("scaled_rasters_output", showWarnings = FALSE)
for (id in names(scaled_rasters)) {
  writeRaster(
    scaled_rasters[[id]],
    filename = file.path("scaled_rasters_output", paste0(id, "_scaled.asc")),
    overwrite = TRUE
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:49:57