Maybe with a raster
X <- matrix(1:20, 4)
r <- raster(X)
r
agg <- as.matrix(focal(r,matrix(1,3,3),sum, pad = T, padValue = 0))
agg
[,1] [,2] [,3] [,4] [,5]
[1,] 14 33 57 81 62
[2,] 24 54 90 126 96
[3,] 30 63 99 135 102
[4,] 22 45 69 93 70
Which method is the faster for large datasets?
X <- matrix(1:1000000, 1000)
S <- matrix(NA, nrow(X), ncol(X))
r <- raster(X)
system.time(
as.matrix(focal(r,matrix(1,3,3),sum, pad = T, padValue = 0))
)
user system elapsed
0.39 0.08 0.47
With a 1000x1000 matrix I was unable to get a result within a reasobable time using the solution proposed by Winsemius (Win 7 x64 8GB RAM)