Learn R Programming

raster (version 1.6-10)

calc: Calculate

Description

Calculate values for a new Raster object from another Raster* object, using a formula. If x is a RasterLayer, fun should be a function that can take a single value as input, and returns a single value (e.g. sqrt). If x is a RasterStack or RasterBrick, and fun returns the same number of values as the input vector (e.g., function(x){ x * 10}) it, calc returns a RasterBrick. But calc returns a RasterLayer if fun takes a vector of values as input, and return a single value (e.g. sum). 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
Raster* object
fun
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{ na.rm Remove NA values, if supported by 'fun' (only relevant when summarizing a mutilayer Raster object into a RasterLayer) 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 RasterBrick
rs <- calc(s, fun=function(x){x * 10})
# recycling by layer
rs <- calc(s, fun=function(x){x * c(1, 5, 10)})

Run the code above in your browser using DataLab