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

使用terra::focal处理分类栅格时如何保留原始分类格式?

保留分类栅格经terra::focal处理后的原始分类格式

使用terra::focal填充分类栅格的缺失数据时,函数返回的栅格会变成数值型,无法保留原始的点分隔分类格式(如"1.1.1")。以下是可复现代码:

set.seed(1)

## Build a raster with categories
r <- terra::rast(matrix(1:25, ncol = 5), crs = "EPSG:3857")
as_tbl <- tibble::as_tibble(r, xy = TRUE)
as_tbl$lyr.1 <- as.factor(paste0(sample(1:10, size = dim(as_tbl)[1], replace = TRUE), ".", sample(1:10, size = dim(as_tbl)[1], replace = TRUE), ".", sample(1:10, size = dim(as_tbl)[1], replace = TRUE)))
newrast <- tidyterra::as_spatraster(as_tbl, crs = "EPSG:3857")
print(newrast)

## Replace cells with NA
newrast[2,2] <- NA
newrast[3,4] <- NA
## plot(newrast)

## Appy the focal function
test <- terra::focal(newrast, w = matrix(1, nrow = 3, ncol = 3), fun = "modal", na.policy = "only", na.rm = TRUE)
print(test)
## plot(test)

注:实际处理的栅格维度为258行、600列、1层。


解决方案

terra::focal处理因子型栅格时,会自动将因子转换为对应的整数编码(数值型)计算。要恢复原始分类格式,只需基于原始栅格的因子水平映射关系,将处理后的数值型栅格转回因子型即可:

  1. 提取原始栅格的因子水平与标签映射
# 获取原始栅格的因子水平和对应标签
cat_levels <- levels(newrast)[[1]]
  1. 执行focal计算
    保留你原有的计算逻辑,得到数值型结果:
test <- terra::focal(newrast, w = matrix(1, nrow = 3, ncol = 3), fun = "modal", na.policy = "only", na.rm = TRUE)
  1. 将数值型结果转回因子型并恢复分类标签
    利用提取的映射关系,把数值替换为原始分类标签:
# 将数值型栅格转换为因子,复用原始的水平标签
test_factor <- terra::as.factor(test)
levels(test_factor) <- cat_levels
  1. 验证结果
    查看处理后的栅格,确认分类格式已保留:
print(test_factor)

关键说明

  • 该方法效率较高,适合大尺寸栅格:仅需一次映射操作,避免了在focal中直接处理字符型数据的性能损耗。
  • 因子水平的映射关系由原始栅格自动提取,无需手动匹配,保证了标签对应关系的准确性。

内容的提问来源于stack exchange,提问作者Sophie Père

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 07:31:11