Skip to content
Prev 86742 / 398502 Next

Matrix indexing in a loop

For 2d here is a solution based on zoo.  It turns the matrix into
a time series and lags it forwards and backwards and does the
same for its transpose in order to avoid index machinations.
The function is called rook2 and it first defines three local
functions, one that converts NAs to zero, one that does
a lag using na.pad = TRUE and one to invoke Lag and
add up the lags:

library(zoo)
rook2 <- function(x, i = 1) {
   na2zero <- function(x) ifelse(is.na(x), 0, x)
   Lag <- function(x, i) na2zero(lag(zoo(x), i, na.pad = TRUE))
   Rook <- function(x, i) Lag(x, i) + Lag(x, -i) + t(Lag(t(x), i) +
Lag(t(x), -i))
   Rook(x, i) / Rook(1+0*x, i)
}

# test
m <- matrix(1:24, 6)
rook2(m)
On 2/17/06, Mills, Jason <Jason.Mills at afhe.ualberta.ca> wrote: