fun
to set the way that the RasterLayers are combined. The number of arguments in the function must match the number of RasterLayer objects. For example, if you combine two RasterLayers you could use multiply: fun=function(x,y){return(x*y)}
percentage: fun=function(x,y){return(100 * x / y)}
. If you combine three layers you could use fun=function(x,y,z){return((x + y) * z)}
You can also supply a function such as sum
, that takes n
arguments. Note that the function must work when its arguments are vectors (not only single numbers)overlay(x, y, ...)
1) x and y are Raster* objects
overlay(x, y, ..., fun, datatype, format, overwrite, progress)
x
a RasterLayer object
y
a RasterLayer object
...
additional RasterLayer objects
fun
the function to be applied. This should be a function that takes two numbers as an argument
filename
filename for the output raster. A valid filename must be provided when the data of the input rasters are on disk
overwrite
logical. If TRUE
, existing files will be overwritten
format
Character. Output file type. See writeRaster
progress
Character. Valid values are "text", "tcltk", "windows" (on that platform only) and ""
}
2) x is a Raster* object, y is missing (this is equivalent to calc
)
overlay(x, fun, overwrite, format, datatype, progress)
x
a RasterLayer object
fun
the function to be appliepd. This should be a function that takes two numbers as an argument
filename
filename for the output raster. A valid filename must be provided when the data of the input rasters are on disk
overwrite
logical. If TRUE
, existing files will be overwritten
format
Character. Output file type. See writeRaster
}sum
or mean
, it would be more direct to use the Raster* objects are arguments to those functions (e.g. sum(r1,r2,r3)
)
In stead of the overlay function you can also use normal aritmethic functions such as *, /, +, -
with RasterLayer objects (see examples), but then you cannot specifiy an output filename.
However, the overlay function should be more efficient when using large data files that cannot be loaded into memory, as the use of the standard arithmetic functions might cause the creation of many temporary files.Arith-methods
r <- raster(ncol=10, nrow=10)
r1 <- init(r, fun=runif)
r2 <- init(r, fun=runif)
r3 <- overlay(r1, r2, fun=function(x,y){return(x+y)})
# long version for multiplication
r4 <- overlay(r1, r2, fun=function(x,y){return(x*y)} )
#use a stack
s <- stack(r1, r2)
r5 <- overlay(s, fun=function(x,y){return(x*y)} )
# use a single RasterLayer (same as calc function)
r6 <- overlay(r1, fun=function(x){return(sqrt(x))} )
# multiplication with more than two layers (make sure the number of RasterLayers matches the arguments of 'fun'
r7 <- overlay(r1, r2, r3, r4, fun=function(a,b,c,d){return(a*b+c*d)} )
# equivalent function, efficient if values can be loaded in memory
r8 <- r1 * r2 + r3 * r4
Run the code above in your browser using DataLab