Search code examples
rmatrixscale

Matrix scale-out


Given a 100x100 matrix, we want to compute a 20x20 matrix, every cell of it represents the mean of a 5x5 square of the original matrix.

How to perform it? (If you have any better name for this operation please comment to rename question).


Solution

  • Here are a couple of options.

    The straightforward approach is to use aggregate() from the raster package:

    m <- matrix(1:10000, ncol=100)
    
    library(raster)
    r <- raster(m)
    as.matrix(aggregate(r, 5))
    
    ## aggregate() also supports non-square aggregation windows
    as.matrix(aggregate(r, c(20, 50)))
    #        [,1]   [,2]   [,3]   [,4]   [,5]
    # [1,]  975.5 2975.5 4975.5 6975.5 8975.5
    # [2,] 1025.5 3025.5 5025.5 7025.5 9025.5
    

    For a more elegant or obfuscated approach (depending on your point of view) use a couple of matrix multiplications:

    m <- matrix(1:10000, ncol=100)
    
    mm <- suppressWarnings(matrix(rep(c(1, rep(0, 20)), each=5), ncol=20, nrow=100))
    (t(mm) %*% m %*% mm)/25