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

如何替换Raster Stack中的Inf与-Inf?代码问题排查求助

替换栅格堆栈中的Inf和-Inf问题解析

我找不到替换栅格堆栈(Raster Stack)中所有Inf和-Inf的方法,以下是我用terra包写的代码,请问我的代码哪里出错了?

library(terra)
#> terra 1.7.29

nrows <- 10
ncols <- 10
set.seed(123) 
r1 <- rast(nrows = nrows, ncols = ncols, xmin = 0, xmax = 10, vals = sample(0:8, nrows * ncols, replace = TRUE))
r1 <- c(rep(list(r1), 10))  
values(r1[[4]]) <- NaN  
values(r1[[7]]) <- NaN 
r1 <- rast(r1)
r2 <- classify(r1, cbind(-Inf, 0, NA))

代码存在的问题

  1. 测试数据无Inf/-Inf值:你当前构造的栅格堆栈里只有NaN和0-8的数值,根本没有Inf或-Inf,所以classify操作不会有任何效果,因为没有匹配的目标值。
  2. classify规则不符合需求:cbind(-Inf, 0, NA)的作用是把**所有小于等于0的值(包括-Inf到0区间)**替换成NA,这和你要替换Inf/-Inf的需求完全不匹配。

正确的解决方法

首先构造包含Inf/-Inf的测试数据,再用以下方法替换:

方法1:使用classify精准匹配Inf和-Inf

library(terra)

# 构造带Inf/-Inf的栅格堆栈
nrows <- 10
ncols <- 10
set.seed(123) 
r <- rast(nrows = nrows, ncols = ncols, xmin = 0, xmax = 10, vals = sample(0:8, nrows*ncols, replace=TRUE))
r_stack <- c(rep(list(r), 10))
# 给第4层加Inf,第7层加-Inf
values(r_stack[[4]])[sample(1:ncell(r), 20)] <- Inf
values(r_stack[[7]])[sample(1:ncell(r), 20)] <- -Inf
r_stack <- rast(r_stack)

# 定义替换规则:把Inf和-Inf都换成NA(或你需要的其他值)
replace_rule <- rbind(
  c(-Inf, -Inf, NA),
  c(Inf, Inf, NA)
)
r_clean <- classify(r_stack, replace_rule)

方法2:使用ifel函数直接判断替换

# 替换Inf和-Inf为NA
r_clean <- ifel(r_stack == Inf | r_stack == -Inf, NA, r_stack)

方法3:直接修改栅格值

# 获取所有值,替换后重新赋值
vals <- values(r_stack)
vals[vals == Inf | vals == -Inf] <- NA
values(r_stack) <- vals
r_clean <- r_stack

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:40:58