# Subset raster stack with logical indeces R

Is it possible to subset a raster stack by indexing on a logical vector?

r1 <- raster(nrow = 100, ncol = 100)
r1[] <- round(runif(ncell(r1), 1, 4), 0)
r2 <- raster(nrow = 100, ncol = 100)
r2[] <- round(runif(ncell(r2), 1, 4), 0)
r3 <- raster(nrow = 100, ncol = 100)
r3[] <- round(runif(ncell(r3), 1, 4), 0)

s <- stack(r1, r2, r3)
names(s) <- c("a", "b", "c")

index <- c(TRUE, FALSE, TRUE)

s[[index]]

Error in .local(x, ...) : not a valid subset

s[index,]

Error in s[index, ] :
logical indices are only accepted if only the first index is used


Desired result: • Do you want to pull the values into a vector, or set cells where FALSE to NA, or something else? Feb 14, 2019 at 23:30

Easiest way to do would be to convert the logical vector into which indices of it are true using... which:

> s[[which(c(TRUE,TRUE,FALSE))]]
class       : RasterStack
dimensions  : 100, 100, 10000, 2  (nrow, ncol, ncell, nlayers)
resolution  : 3.6, 1.8  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
names       : a, b
min values  : 1, 1
max values  : 4, 4


Here's what which does on a logical vector:

> which(c(TRUE, FALSE, TRUE))
 1 3
> which(c(FALSE, FALSE, TRUE))
 3
>

• I knew I was missing something obvious. Thank you this is working great! Feb 14, 2019 at 23:33