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

如何解决从ASC堆叠栅格图层提取值到物种出现CSV数据的报错?

从ASC堆叠栅格提取值到物种出现CSV的问题解决

操作步骤及问题

初始代码

#Loading climate data
bio6 <- raster("bio_06.asc")
bio5 <- raster("bio_05.asc")
predictors <- stack(bio5, bio6) predictors  # 此处存在语法错误,多余的`predictors`

#Loading occurrence data which is in long and lat
occ <- read.csv("presence_locations.csv")[,1]

提取时的错误

执行presvals <- extract(predictors, occ)时触发错误:

Error in extract(predictors, occ) : 
  object of type 'S4' is not subsettable

数据详情

  • predictors(栅格堆叠):
> predictors
class      : RasterStack 
dimensions : 9605, 7866, 76024090, 2  (nrow, ncol, ncell, nlayers)
resolution : 0.0001297718, 0.0001297718  (x, y)
extent     : 35.5506, 36.65584, 35.58337, 37.13761  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
names      : bio_05, bio_06 
  • occ(物种出现数据):
> occ
Longitude Latitude
1    35.16556 36.25056
2    36.01378 36.55494
3    36.26056 36.97625

背景点提取问题

提取背景点时返回全NA值:

# background data
backg <- randomPoints(predictors, 1000)
absvals <- extract(predictors, backg)
> absvals
        bio_05 bio_06
   [1,]     NA     NA
   [2,]     NA     NA

解决方案

1. 修正物种出现数据的读取与语法错误

  • 你读取occ时仅保留了第一列,但extract需要包含经度、纬度的两列坐标数据作为输入,修改读取代码:
# 读取完整的坐标数据
occ <- read.csv("presence_locations.csv")
# 或明确指定坐标列(确保列名匹配)
occ_coords <- occ[, c("Longitude", "Latitude")]
  • 同时修正栅格堆叠代码的语法错误:
predictors <- stack(bio5, bio6)
  • 重新执行提取:
presvals <- extract(predictors, occ_coords)

2. 筛选栅格范围内的有效坐标

从predictors的范围可知,经度区间为35.5506~36.65584,而occ的第一个点经度35.16556超出范围,这类点提取结果必然为NA。可筛选有效坐标:

occ_in_extent <- occ[occ$Longitude >= xmin(predictors) & occ$Longitude <= xmax(predictors) &
                     occ$Latitude >= ymin(predictors) & occ$Latitude <= ymax(predictors), ]
presvals <- extract(predictors, occ_in_extent)

3. 解决背景点全NA问题

背景点全NA大概率是栅格本身无有效值(全为NA),按以下步骤排查:

  • 检查栅格数据是否有效:
# 查看单个栅格的非NA像元数量,返回0则说明栅格全为NA
cellStats(bio5, "count")
  • 若栅格全为NA,需检查ASC文件是否损坏或路径是否正确;若栅格有有效值,尝试指定na.rm=TRUE生成背景点:
backg <- randomPoints(predictors, 1000, na.rm = TRUE)
absvals <- extract(predictors, backg)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:10:15