Given a matrix, I want to find the sum of the neighbors for each element (so the result is a matrix). The neighbors are the values above, below and beside the given element ,if they exist (not considering the diagonal elements).
Example:
> z = matrix(1:9, 3, 3, byrow=T)
> z
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
And the expected result is :
> result
     [,1] [,2] [,3]
[1,]    6    9    8
[2,]   13   20   17
[3,]   12   21   14
What is the simplest way I can do this in R without using loops?
One way would be to make matrices with the neighbor on each side and add them together.
rbind(z[-1,],0) + rbind(0,z[-nrow(z),]) + cbind(z[,-1],0) + cbind(0,z[,-ncol(z)])
##      [,1] [,2] [,3]
## [1,]    6    9    8
## [2,]   13   20   17
## [3,]   12   21   14
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With