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