'Creating a raster stack of algorithms using nested loops to iterate through all possible band combination

All,

I am not able to directly stack these images inside of the loop. My only work around was to write each results then stack the images after the loop was completed. I would like to find an apply function that would allow me to do the same thing and I need to find a way to stack these rasters inside the loop instead of creating intermediate data by saving the output.

Any insight into this process would appreciated!

# Create function
Loop <- function(X,B1,B2){
  S2_ext <- extent(S2) # Create raster template
  2BDA_Stack <- raster(S2_ext)
   for(i in B1){
     for(j in B2){
      2BDA <- X[[i]]/X[[j]]
      2BDA_Stack <- stack(2BDA_Stack, 2BDA)
# I WANT TO REMOVE THIS STEP
      writeRaster(x = 2BDA,
                  filename= paste("...",'Chl_2BDA_',i,j),
                  format = "GTiff", # save as a tif
                  datatype='FLT4S', # save as a float
                  overwrite = T) #Overwrites same named file
     }
   }
}

#Run Function
2BDA_Loop(X=S2,B1=1:6,B2=1:6)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source