R – Importing and Handling Multiple Stacked Raster Images

landsatrrasterremote sensing

I would like to import all multiple mosaic rasters (each mosaic is composed by 7 layers) from indicated folder into my R. Then access them as single multilayers rasters.

enter image description here

So I did:

# read all mosaics named "mos....img" in R    
raster_data<-list.files(path=getwd(), pattern="mos.*.img$") 
# read files as rasters
s <- stack(raster_data)
# check my imported rasters p.ex. raster n°8 from "s" raster stack
s[[8]]         

and my raster s[[8]] contain only 1 layer, so not the whole mosaic was imported!

nlayers(s[[8]])
[[1]]

If I read each mosaic separately, it works:

# read 1 mosaic (composed by 7 bands)
mosaic1<-brick("mosaic1.img")
# extract one band
band4<-subset(mosaic1, 4)

Why "stack" tool doesn´t import whole mosaics but only one band of the mosaic and how it is possible to arrange it?

Best Answer

Have a look at nlayers(s). The returned number of layers will equal 28 - at least for the above example with 4 multi-layer objects encompassing 7 layers each. Applying stack to multiple multi-layer files results in one huge 'RasterStack' object, i.e. all the single multi-layer objects are appended to one another.

If you would like to have separate stacks for each file, I would recommend using

s <- lapply(raster_data, stack)

which results in a list of 'RasterStack' objects, each including 7 layers rather than one huge stack. You may then access particular layers, e.g. the 2nd layer of the 3rd 'RasterStack' object, by

s[[3]][[2]]
Related Question