# Subset raster stack in R by a vector of number sequences?

I have a large raster stack that I need to subset by somewhat irregular time spans. I'd like to do something like this:

``````rstack[[c(1:3, 4:8, 9:15)]]
``````

But there are 30 sequences like the ones above that I need to subset by, and I'd rather not type them all in manually.

I'm wondering if I can create a vector object, something like this:

``````vec <- c(1:3, 4:8, 9:15)
rstack[[vec]]
``````

But based off of a data frame where I have the start, end values for the sequences to automate the process?:

``````df <- tibble(
start = c(1, 4, 9),
end = c(3, 8, 15)
)

# A tibble: 3 x 2
start   end
<dbl> <dbl>
1     1     3
2     4     8
3     9    15
``````
• How about `raster::stack(rstack[[1:3]], rstack[[4:8]], rstack[[9:15]])` ? – Kazuhito Aug 31 '19 at 6:48

## 1 Answer

With a data frame (not a tibble) like this:

``````> layers = data.frame(start=c(1,4,11),end=c(3,8,15))
> layers
start end
1     1   3
2     4   8
3    11  15
``````

Note I made it so that there's a gap in the total sequence so I can see it is doing something...

Do this to get the vector of merged sequences:

``````> unlist(apply(layers,1,function(s){s:s}))
  1  2  3  4  5  6  7  8 11 12 13 14 15
``````

Assign that and use it to subset your stack:

``````> keep = unlist(apply(layers,1,function(s){s:s}))
``````

`s` is my stack with 20 layers:

``````> dim(s)
  3  4 20
``````

subset to get 13 back:

``````> kept = s[[keep]]
> dim(kept)
  3  4 13
>
``````