Performing several hundred raster multiplications I have several hundred "A" rasters, numbered from 001_A.tif to 100_A.tif.

I also have several hundred "B" rasters, numbered from 001_B.tif to 100_B.tif.

I want to multiply them like this:

001_A * 001_B = 001_result
002_A * 002_B = 002_result
003_A * 003_B = 003_result
.
.
.


I have a loop in R which works fine, but it is relatively slow: 

library(raster)

A_Files &lt;- list.files(pattern="A.tif") # files A
All_A &lt;- unique(A_Files)

B_Files &lt;- list.files(pattern="B") # files B
All_B &lt;- unique(B_Files)

for (i in 1:100) {
  A.i &lt;- All_A[i]
  B.i &lt;- All_B[i]

  Raster_A.i &lt;- raster(A.i) # create rasters from files A
  Raster_B.i &lt;- raster(B.i) # create rasters from files B

  Result.i &lt;- (Raster_A.i * Raster_B.i) # multiplying A by B

  writeRaster(Result.i, paste(A.i, "_result.tif", sep = ""), datatype='FLT4S',
 overwrite=TRUE) # write results in .tif format with the name "001_A_result.tif"
    } 


Is there a way to speed it up?
Rasters

Rasters are highly memory intensive in R's already fragile memory space. However, one does not necessarily need to read a raster into memory each time. In fact, it is highly frowned upon to read in a raster in that way as it just eats up so much memory and is computationally intensive.

stack()'s beauty

It's much better to make a stack of rasters as it does not load them into memory, but opens their file location.

library(raster)

A_Files &lt;- list.files(pattern="A.tif") # files A
All_A &lt;- stack(unique(A_Files))

B_Files &lt;- list.files(pattern="B") # files B
All_B &lt;- stack(unique(B_Files))


Notice, all of the elements are now in a "vectorized" form. 

overlay() to calculate

From here, we can use overlay() to perform a calculation. Note, since the number of layers is equivalent between (ALL_A) and (ALL_B) we do not need to worry about an element being repeated. 

x &lt;- overlay(All_A, All_B, fun=function(x,y) x*y )


Export

The only downside to this approach is you will have to go through a loop to export the answers: 

out &lt;- unstack(x)
outputnames &lt;- paste0(seq_along(out), "_result.tif")
for(i in seq_along(out)){ writeRaster(out[[i]], file=outputnames[i]) }


References

For multiplying stacks see:


overlay
calc


For more information on stacks (see bricks as well)


stack
brick