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

如何在R语言中将栅格中[10,30]区间内的值设为NA?

Fixing the Issue of Setting Raster Values in [10,30] to NA in R

Hey there, let's figure out where your code went wrong and fix it step by step:

First, your code has two main issues:

  • Syntax problem: The line values = r[r<= c(10,30)] = NA uses invalid continuous assignment syntax in R, and the condition r<= c(10,30) will cause unexpected results due to R's recycling rule (it will compare each value in r to 10, then 30, repeating until all values are checked—definitely not what you want for a range check).
  • Logic problem: To target values between 10 and 30 (inclusive), you need to use a combined condition >=10 & <=30, not a vector in the comparison.

Here are two reliable ways to achieve your goal:

Method 1: Direct Index Assignment (Simplest for This Case)

# First, recreate your raster object
r <- raster(ncols=10, nrows=10)
r[] <- sample(50, 100, replace=T)

# Set values between 10 and 30 to NA
r[r[] >= 10 & r[] <= 30] <- NA

The r[] extracts all cell values from the raster. We use the logical condition >=10 & <=30 to select cells in the target range, then assign NA directly to those positions.

Method 2: Use reclassify (Better for Complex Reclassification)

If you ever need to handle multiple reclassification ranges later, the reclassify function from the raster package is more flexible:

# Define a reclassification matrix: start of range, end of range, replacement value
reclass_matrix <- matrix(c(10, 30, NA), ncol=3, byrow=TRUE)
r <- reclassify(r, reclass_matrix)

This method scales well if you need to replace values in multiple non-overlapping ranges with different values (or NA).

You can verify the result by running summary(r)—you'll see that values from 10 to 30 are no longer present, replaced by NA instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:12:15