Learn R Programming

raster (version 1.4-10)

calc: Calculate

Description

Calculate values for a new Raster object from another Raster* object, using a formula. If x = "RasterLayer", fun should be a function that can take a single value as input, and returns a single value (e.g. sqrt). If x = "RasterStackBrick", fun should be a function that takes a vector of values as input, and returns a single value (e.g. sum; to return a RasterLayer), or a function with the same number of values as the input vector (e.g., function(x){ x * 10} to return a RasterStack/Brick. In many cases, what can be achieved with calc in a more intuitive 'raster-algebra' notation (see Arith-methods). For example, r <- r * 2 rather than r <- calc(r, fun=function(x){x * 2}. However, calc should be faster when using complex formulas on large datasets. With calc it is also easier to set output file preferences if applicable. See (overlay) to use functions that refer to specific layers, like (function(a,b,c){a + sqrt(b) / c})

Usage

calc(x, fun, ...)

Arguments

x
a Raster* object
fun
a function
...
Additional arguments. See Details

Value

  • a Raster* object

Details

The following additional arguments can be passed, to replace default values for this function rll{ filename Output filename (optional) format Character. Output file type. See writeRaster datatype Character. Output data type. See dataType overwrite Logical. If TRUE, "filename" will be overwritten if it exists progress Character. "text", "window", or "" (the default, no progress bar) }

See Also

overlay , reclass, Arith-methods, Math-methods

Examples

Run this code
r <- raster(ncols=36, nrows=18)
r[] <- 1:ncell(r)

# multiply values with 10
fun <- function(x) { x * 10 }
rc <- calc(r, fun)

# set values below 100 to NA. 
fun <- function(x) { x[x<100] <- NA; return(x) }
rc <- calc(r, fun)

# set NA values to -9999
fun <- function(x) { x[is.na(x)] <- -9999; return(x)} 
rc <- calc(rc, fun)

# using a RasterStack as input
s <- stack(r, r*2, sqrt(r))
# return a RasterLayer
rs <- calc(s, sum)

# return a RasterStack
rs <- calc(s, fun=function(x){x * 10})
# return a RasterStack, using recycling by layer
rs <- calc(s, fun=function(x){x * c(1, 5, 10)})

Run the code above in your browser using DataLab