如何使用 R 中的 terra 包对 SpatRaster 进行子集化?

问题描述 投票:0回答:1

我有一个包含多个类别的栅格,我只对其中一个类别(vegClass)感兴趣。

veg <- terra::rast("~/SVTM_NSW_Extant_PCT_vC2_0_M2_0_106/SVTM_NSW_Extant_PCT_vC2_0_M2_0_5m.tif")
activeCat(veg) <- 4 #set category of interest to veg class 
veg


class       : SpatRaster 
dimensions  : 1207, 1463, 1  (nrow, ncol, nlyr)
resolution  : 0.0002777778, 0.0002777778  (x, y)
extent      : 142.2135, 142.6199, -31.33736, -31.00208  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat GDA94 
source(s)   : memory
varname     : 1_Second_DEM_MNP_N 
categories  : PCTID, PCTName, vegForm, vegClass, form_PCT, labels 
name        :                    vegClass 
min value   :              Not classified 
max value   : Riverine Sandhill Woodlands 

我只想保留一些值,并将其他所有值设置为 NA。

values_to_keep <- c("Stony Desert Mulga Shrublands", "Gibber Chenopod Shrublands", "Inland Rocky Hill Woodlands")

我不知道如何做到这一点。我尝试将其转换为数据框并进行过滤,但栅格没有 xy 列,因此当我尝试将其转换回来时坐标数据会丢失。如有任何帮助,我们将不胜感激!

r raster spatial terra
1个回答
0
投票

您可以使用

subst
包中的
terra
函数来实现此功能

library(terra)

#Create some raster data
set.seed(0)
r <- rast(nrows=10, ncols=10)
values(r) <- sample(3, ncell(r), replace=TRUE)
cls <- data.frame(id=1:4, vegClass = c("Stony Desert Mulga Shrublands", 
                                  "Gibber Chenopod Shrublands", 
                                  "Inland Rocky Hill Woodlands",
                                  "Not classified"))
levels(r) <- cls

#Use subst function to select only intended classes and set others NA
test <- subst(r, from=c("Stony Desert Mulga Shrublands", 
                    "Gibber Chenopod Shrublands", 
                    "Inland Rocky Hill Woodlands"), 
               to=c("Stony Desert Mulga Shrublands", 
                 "Gibber Chenopod Shrublands", 
                 "Inland Rocky Hill Woodlands"),
               others=NA)
© www.soinside.com 2019 - 2024. All rights reserved.