Drop a layer in raster stack

Viewed 360

I have issue using drop layer/subset function to remove raster layer from raster stack that have min and max value==0. Please help me correcting this syntax.

Ls_AOI_3_r_sel_stk_v1 <- dropLayer(Ls_AOI_3_r_sel_stk_crop, (maxValue(Ls_AOI_3_r_sel_stk_crop)==0) & (maxValue(Ls_AOI_3_r_sel_stk_crop)==0))
1 Answers

Please find below one possible solution using the terra library (which is an improved version of the raster library)

Reprex

  • 1 - Creating a dummy raster r of class SpatRaster
library(terra)

A <- rast( nrows=10, ncols=10, xmin=0, xmax=10 )
B <- rast( nrows=10, ncols=10, xmin=0, xmax=10 )
C <- rast( nrows=10, ncols=10, xmin=0, xmax=10 )

values(A) <- 1:100
values(B) <- 0:99
values(C) <- rep(0,100)

r <- rast(list(A,B,C))

names(r) <- c("red","green","blue")

# To what looks like 'r'
r
#> class       : SpatRaster 
#> dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
#> resolution  : 1, 18  (x, y)
#> extent      : 0, 10, -90, 90  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 
#> sources     : memory  
#>               memory  
#>               memory  
#> names       : red, green, blue 
#> min values  :   1,     0,    0 
#> max values  : 100,    99,    0
  • 2 - Code to select layers where min and max are different from 0
r[[minmax(r)[1,] != 0 & minmax(r)[2,] != 0]]
  • 3 - Output (only the "red" layer has been selected)
#> class       : SpatRaster 
#> dimensions  : 10, 10, 1  (nrow, ncol, nlyr)
#> resolution  : 1, 18  (x, y)
#> extent      : 0, 10, -90, 90  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 
#> source      : memory 
#> name        : red 
#> min value   :   1 
#> max value   : 100

Created on 2022-02-09 by the reprex package (v2.0.1)

Related