Is there an R function to get the sum of neighboring values of a matrix (for varying radius)?

I have a matrix M (say r rows and c columns) and I would like to get the sum for each matrix element based on it's neighbors and create a new matrix M2. The word neighbor could be within a radius of 1 (which is often called the Moore neighborhood in Cellular Automata theory) or the radius could be a different than 1, say, 2, 3, etc.

For a particular cell in the matrix M, say somewhere in the middle. Let's say position (i,j); then the (i,j)th cell has "eight" neighbors given by,

(i-1, j-1), (i-1, j), (i-1, j+1), (i, j-1), (i, j+1), (i+1, j-1), (i+1, j), (i+1, j+1).

I want to create a matrix M2 that calculates the sum of the (i,j)th cell plus its eight neighbors. The same is repeated for all cells (cells along the boundaries need to be treated specially since they don't necessarily have eight neighboring cells). The above idea is for radius 1 but the code I trying to develop needs to be generic for any r.

I thought about two possible ideas;

  1. Add a padding around the matrix M (dummy rows and columns filled with 0s). The padding size depends on the radius.
  2. Use a combination of which(), apply(), unlist() etc. Quite complicated for my understanding.
rm(list = ls())

r <- 4
c <- 4

n <- r*c

(M <- matrix(1:n, r, c))

addresses <- expand.grid(x = 1:r, y = 1:c)

Got this code in the same forum

z <- rbind(c(-1,0,1,-1,1,-1,0,1),c(-1,-1,-1,0,0,1,1,1))

get.neighbors <- function(rw) {
  # Convert to absolute addresses 
  z2 <- t(z + unlist(rw))
  # Choose those with indices within mat 
  b.good <- rowSums(z2 > 0)==2  &  z2[,1] <= nrow(M)  &  z2[,2] <= ncol(M)

apply(addresses,1 , get.neighbors) # Returns a list with neighbors


Essentially, M2 for radius = 1 must be the sum of the current cell plus the neighbors.

M = [ 1  5   9  13
      2  6  10  14
      3  7  11  15
      4  8  12  16]

M2 = [ 14  33  57 46
       24  54  90 72
       30  63  99 78
       22  45  69  54]

How do I go about getting matrix M2 in R? What about if radius for more than 1?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.