How to write every raster from a list of rasters?
If you have a list of raster
objects with equal extent and resolution, it's probably easiest to stack
them first and then use writeRaster
with bylayer=TRUE
.
For example:
library(raster)
Create some dummy data
L <- setNames(replicate(3, raster(matrix(runif(100), 10))), c('A', 'B', 'C')) L # $A # class : RasterLayer # dimensions : 10, 10, 100 (nrow, ncol, ncell) # resolution : 0.1, 0.1 (x, y) # extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax) # coord. ref. : NA # data source : in memory # names : layer # values : 0.01015837, 0.9958344 (min, max) # # # $B # class : RasterLayer # dimensions : 10, 10, 100 (nrow, ncol, ncell) # resolution : 0.1, 0.1 (x, y) # extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax) # coord. ref. : NA # data source : in memory # names : layer # values : 0.01501442, 0.9975531 (min, max) # # # $C # class : RasterLayer # dimensions : 10, 10, 100 (nrow, ncol, ncell) # resolution : 0.1, 0.1 (x, y) # extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax) # coord. ref. : NA # data source : in memory # names : layer # values : 0.01136738, 0.9983568 (min, max)
And stack them and write them out to separate tifs
writeRaster(stack(L), names(L), bylayer=TRUE, format='GTiff')
This will write out the three layers to tifs with names defined by the layer names, i.e. A.tif
, B.tif
, and C.tif
.
Alternatively, if the rasters in the list are not of equal extent/res, you can iterate over the list and write each out in turn:
mapply(writeRaster, L, names(L), 'GTiff')
I use mapply
above for convenience, since it allows easy passing of layer names as file names.
Another solution would be to create a simple for
loop.
for (i in 1:length(L)) {
writeRaster(L[[i]], names(L[[i]]), format='GTiff')
}
The rasters will be saved in the path you specified as working directory