rar
rar

Reputation: 924

Extracting individual layers from raster stack in loop

I have a RasterStack with 18 layers. I need to extract all layers as individual layers. But I do not want to write these files to disk (so not using writeRaster function). I just want to extract them to the work space. When I use a for loop, I get a single layer (the last one), and no other layer is saved to the workspace.

for(i in 1:nlayers(r)) {
  X <- r[[i]]
}

What is is it that I am missing in this loop?

Upvotes: 3

Views: 4930

Answers (1)

jbaums
jbaums

Reputation: 27398

You can use unstack and list2env for this:

library(raster)
s <- stack(replicate(5, raster(matrix(runif(100), 10))))

s
## class       : RasterStack 
## dimensions  : 10, 10, 100, 5  (nrow, ncol, ncell, nlayers)
## resolution  : 0.1, 0.1  (x, y)
## extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
## coord. ref. : NA 
## names       :     layer.1,     layer.2,     layer.3,     layer.4,     layer.5 
## min values  : 0.011998514, 0.003202582, 0.020602761, 0.023202067, 0.000311564 
## max values  :   0.9814509,   0.9963595,   0.9931403,   0.9766521,   0.9977042

ls()
## [1] "s"

list2env(setNames(unstack(s), names(s)), .GlobalEnv)
ls()
## [1] "layer.1" "layer.2" "layer.3" "layer.4" "layer.5" "s"   

We unstack the RasterStack to a list of single raster layers, assign the layer names as the list element names, and then assign each element to an object with the corresponding name, in the specified environment (the global environment, above).

Be aware that objects in the environment will be overwritten if their names conflict with the names of the list elements.

See ?list2env for further details.

Upvotes: 3

Related Questions