I have created a list of rasters - "norm" and run a several loops. Now I would like to write every created raster from "norm" (containing 1 layer) into one raster, having its specific name.
# I can get the rasters names
rst.names<-c(1:length(norm))
for(i in 1:length(norm)){
rst.names1<-names(norm[[i]])
rst.names[[i]]<-rst.names1
}
To write and save a rasters I have found a very useful answer on https://stackoverflow.com/questions/14890369/how-to-write-rasters-after-stacking-them
where they use to respond my question (modified):
unst_norm<- unstack(norm)
for(i in 1:lenght(unst_norm)){writeRaster(unst_norm[[i]], file=rst.names[i])}
However if I use "unstack" I have this error:
Error in stats::as.formula(form) :
argument "form" is missing, with no default
and I can´t find any help for that.
I can use "unlist" instead of "unstack" but it doesn't seem to work...
but I still get an error:
Error in .local(.Object, ...) : Unable to create dataset
Please, any ideas where the problem could be? Or, how to automatically write and save all rasters from raster list?
Answer
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.
No comments:
Post a Comment