r <- raster(ncols=36, nrows=18, xmn=0)
r[] <- runif(ncell(r))
# 3x3 mean filter
r3 <- focal(r, w=matrix(1/9,nrow=3,ncol=3))
# 5x5 mean filter
r5 <- focal(r, w=matrix(1/25,nrow=5,ncol=5))
# Gaussian filter for square cells
fgauss <- function(sigma, n=5) {
m <- matrix(nc=n, nr=n)
col <- rep(1:n, n)
row <- rep(1:n, each=n)
x <- col - ceiling(n/2)
y <- row - ceiling(n/2)
# according to http://en.wikipedia.org/wiki/Gaussian_filter
m[cbind(row, col)] <- 1/(2*pi*sigma^2) * exp(-(x^2+y^2)/(2*sigma^2))
# sum of weights should add up to 1
m / sum(m)
}
gf=fgauss(1.5)
rg <- focal(r, w=gf)
# The max value for the lower-rigth corner of a 3x3 matrix around a focal cell
f = matrix(c(0,0,0,0,1,1,0,1,1), nrow=3)
f
rm <- focal(r, w=f, fun=max)
# global lon/lat data: no 'edge effect' for the columns
xmin(r) <- -180
r3g <- focal(r, w=matrix(1/9,nrow=3,ncol=3))
Run the code above in your browser using DataLab