4
votes

I have a question about stack() Raster Layers.

Usually I stack() Raster Layers like that:

stack(RasterLayer1,RasterLayer2,RasterLayer3) # e.g. for 3 Layers

My Question is, how can I stack() Raster Layers without typing in every Raster Layer?

For example: n is the amount of Raster Layers (e.g. 12), all named band.

I created n-Raster Layers and now I want to stack all without typing n-times the Name of the Raster Layers. So instead of typing:

stack(band1,band2,band3,band4,band5,band6,band7,band8,band9,band10,band11,band12)

I want to short that by stack(band[n]), but that doesn't work.

And if I create a list of all bands, I can't stack that list, because they don't appear in my Working Directory because I just created them.

Can anyone help me, please?

3
stack takes a list of rasters, or a vector of file names, or a single filename that has multiple bands. we need more info about what you have, folders of files, or loops? that create objects, or? You can use lapply, ls, and get to collate free floating names in the workspace, but better to unpick a littlemdsumner
I have raster data which i read in with a Loop, rename them and resample every single Layer. In the End i have n Raster Layers named different from the original raster data i have in my working Directory. That's why list.files() don't work, because i don't save the renamed and resampled Raster Layers. I don't even know if it's possible to stack() Raster Layers from a list if they're not in the Working Directory.A.F.

3 Answers

4
votes

If your data is in a directory, you can use a search pattern (for example: *.tif, *.grd,...) and store it in a variable.

bands <- list.files(path=".",pattern="*.tif",full.names=TRUE,recursive=TRUE)

now assume that your data is called:

band_01.tif
band_02.tif
band_03.tif
band_04.tif
band_05.tif
band_06.tif
band_07.tif

then you can stack for example:

data_stack <- stack(bands) #stack all data
data_stack <- stack(bands[1:3]) #stack 1,2 and 3 data
data_stack <- stack(bands[c(1,3,5,7)]) 
2
votes

I would recommend not to save them under separate variables like band1,band2,... but instead store them in a list. Here an example:

#Create empty rasters
ras1<- raster()
ras2<- raster()

#Initialise and append to list
list_ras <- list()
list_ras[[1]] <- ras1
list_ras[[2]] <- ras2

#Stack single bands
ras_stack <- stack(list_ras[[1]], list_ras[[2]])

#Stack all bands
ras_stack <- stack(list_ras)
1
votes

Here is an other approach using mget:

# Generate some data
library(raster)
r <- raster()
r[] <- runif(ncell(r))
for (i in 1:10) assign(paste0("r", i), r)

# create a stack      
stack(mget(ls(pattern = "^r.+")))