问题
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?
回答1:
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
回答2:
Here's one way to do it. I won't claim it's the simplest, but it certainly avoids looping.
m <- matrix(1:16, 4, 4, byrow=TRUE)
result <- array(sapply(seq_along(m), function(i) {
ind <- which(col(m) == col(m)[i] & abs(row(m)[i] - row(m)) == 1 |
row(m) == row(m)[i] & abs(col(m)[i] - col(m)) == 1)
sum(m[ind])
}), dim(m))
result
[,1] [,2] [,3] [,4]
[1,] 7 10 13 11
[2,] 16 24 28 23
[3,] 28 40 44 35
[4,] 23 38 41 27
来源:https://stackoverflow.com/questions/22572901/for-each-element-in-a-matrix-find-the-sum-of-all-of-its-neighbors