我不认为 data.table 是正确的工具。它的行索引概念不太适合此操作(尽管我可能会吐出旧信息):
X <- matrix(1:20, 4)
S <- matrix(NA, nrow(X), ncol(X))
for (x in row(X)){
for (y in col(X)){
S[x,y] <- sum(X[abs( row(X) - x)<2 & abs( col(X)-y)<2 ])
}}
S
#---------
[,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
考虑到效率,这个算法会更快......但仍然比raster::focal慢得多
rows <- dim(X)[1]; cols<-dim(X)[2]
for (x in row(X)){
for (y in col(X)){
S[x,y] <- sum(X[max(1,x-1):min(rows, x+1) ,max(1,y-1):min(cols,y+1) ])
} }
也许更快:
system.time( S2 <- X+
rbind ( cbind(X[-1,-1], 0), 0)+ #diagonal shifts of the matrix
rbind( cbind( 0, X[-1,-1000]) , 0)+
rbind( 0, cbind( X[-1000, -1] , 0))+
rbind(0, cbind( 0,X[-1000,-1000]) )+
rbind( X[ -1, ], 0)+ # these create the sums on the same rows or columns
rbind(0, X[-1000, ])+
cbind( X[ , -1],0)+
cbind(0, X[ , -1000]) )
user system elapsed
0.563 0.065 0.630
> identical(S,S2) # compare to the focal-method above
[1] TRUE