2

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?

jbaums
  • 27,115
  • 5
  • 79
  • 119
rar
  • 894
  • 1
  • 9
  • 24
  • That's because you keep overwriting `X` with the next layer, so.. `X` will be the last layer, since that one does not get overwritten. What's wrong with keeping them in `r`? Or do you specifically need 18 different variables? – slamballais Feb 17 '16 at 13:26
  • All the layers represent different variables so I was thinking of extracting them separately. But for now I am using `r[[i]]` to access different layers. – rar Feb 17 '16 at 13:51
  • 2
    Well, you could create individual variables with `vars <- paste0("X",1:18); for (i in 1:18) assign(vars[i],r[[i]])`. This will create 18 variables (`X1` up to `X18`). However, keep in mind that from then on you have 18 separate objects, which makes automation and much more difficult than using `r[[i]]`. Also read: http://stackoverflow.com/a/17559641/5805670 – slamballais Feb 17 '16 at 13:56

1 Answers1

2

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.

jbaums
  • 27,115
  • 5
  • 79
  • 119