2

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:

enter image description here

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

1 Answer 1

3

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] 1 3
> which(c(FALSE, FALSE, TRUE))
[1] 3
> 
1
  • I knew I was missing something obvious. Thank you this is working great! Feb 14, 2019 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.