How to select which layers I want to keep in a new SpatRaster

rrasterterra

I have a raster with 10 layers. I want to split it up into two separate objects, one containing the first 5 layers, and one containing the second 5 layers. Reading the help file for rast(), it seems like when I create a new SpatRaster I can select the NUMBER of layers that will be retained from the original, but I don't see how I can specify WHICH layers will be retained from the original. If I just specify 5 layers, is it only keeping the first 5 layers?

x <- rast(nlyrs = 10, nrows=108, ncols=21, xmin=0, xmax=10)

y <- rast(x, nlyrs = 5)

Best Answer

You can simply index the rasters. In this example we will subset the (1, 3-4, 10) rasters. Note the double brackets.

library(terra)
x <- rast(nlyrs = 10, nrows=108, ncols=21, xmin=0, xmax=10)
  y <- x[[c(1, 3:4, 10)]]

For your needs you can use

y1 <- x[[1:5]]
y2 <- x[[6:10]] 

Unlike the raster package, to add a raster you can simply use concatenate.

y <- c(y, x[[2]])

There are also some formal methods in terra, see; subset, selectRange and, add