focalFilter(x, filter, fun=sum, filename="", na.rm=FALSE, pad=TRUE, padValue=NA, ...)
TRUE
, NA
values are ignored. Except for some special cases, this is generally not a good idea in this function because it will unbalance the effect of the filter!TRUE
, additional 'virtual' rows and columns are padded to x
such that there are no edge effects. This can be useful when a function needs to have access to the central cell of the filter.x
is unprojected (latiude/longitude) and spans all longitudes (-180 to 180 degrees)focalFilter
uses a matrix of weights for the neigbhorhood of the focal cells, together with a function (normally sum
).
For example, filter=matrix(1/9, nrow=3, ncol=3)
would be equivalent to mean
with ngb=3
in the focal
function.
Gaussian filter:
filter=matrix(c(1,2,3,2,1,2,3,4,3,2,3,4,5,4,3,2,3,4,3,2,1,2,3,2,1), nrow=5)/65
Laplacian filter:
filter=matrix(c(0,1,0,1,-4,1,0,1,0), nrow=3)
Sobel filter:
filter=matrix(c(1,2,1,0,0,0,-1,-2,-1) / 4, nrow=3)
Another example:
filter=matrix(c(0,0,0,0,1,1,0,1,1), nrow=3)
and fun=max
returns the max value for the lower-rigth corner of a 3x3 matrix
around a focal cell
The filter must have uneven sides (e.g., 3x3 or 5x5), but if you need uneven sides, you can add a column or row with weights of zero.
The following additional arguments can be passed, to replace default values for this function
overwrite
Logical. If TRUE
, "filename" will be overwritten if it exists
format
Character. Output file type. See writeRaster
datatype
Character. Output data type. See dataType
progress
Character. "text", "window", or "" (the default, no progress bar)
}focal
r <- raster(ncols=36, nrows=18)
r[] <- runif(ncell(r))
gf=matrix(c(1,2,3,2,1,2,3,4,3,2,3,4,5,4,3,2,3,4,3,2,1,2,3,2,1), nrow=5)/65
rff <- focalFilter(r, filter = gf)
Run the code above in your browser using DataLab