# [R] zero-offset matrices

Jonathan Rougier J.C.Rougier at durham.ac.uk
Tue Mar 2 16:29:22 CET 1999

```On Tue, 2 Mar 1999, Prof Brian Ripley wrote:

> > Has anyone written subscripting methods for matrices which are indexed
> > from zero? i.e. functions such as "[.zoffset" and "[<-.zoffset" which

> No, but should it not be very easy? Just check if the subscript is
> numeric, add 1, call NextMethod? Let's see:

>>> [showing how it is not easy!]

> So perhaps someone who really understands R will tell me what is going
> on here.

I have had a similar experience!  I am not sure what is going on either,
but I have a working solution as follows ...

"[.zoffset" <-
function (x, i = rep(T, nrow(x)), j = rep(T, ncol(x)), ...)
{
x <- unclass(x)
if (!is.logical(i)) {
tmp <- rep(F, nrow(x))
tmp[i + 1] <- T
i <- tmp
}
if (!is.logical(j)) {
tmp <- rep(F, ncol(x))
tmp[j + 1] <- T
j <- tmp
}
x[i, j, ...]
}

"[<-.zoffset" <-
function (x, i = rep(T, nrow(x)), j = rep(T, ncol(x)), value)
{
x <- unclass(x)
if (!is.logical(i)) {
tmp <- rep(F, nrow(x))
tmp[i + 1] <- T
i <- tmp
}
if (!is.logical(j)) {
tmp <- rep(F, ncol(x))
tmp[j + 1] <- T
j <- tmp
}
x[i, j] <- value
structure(x, class = "zoffset")
}

It is a bit clumsy, but it handles all the usual subscripting cases,
including things like

fred[, 0:2] <- NA

Cheers, Jonathan.

Jonathan Rougier                       Science Laboratories
Department of Mathematical Sciences    South Road
University of Durham                   Durham DH1 3LE

"[B]egin upon the precept ... that the things we see are to be
weighed in the scale with what we know"  (Meredith, 1879, The Egoist)

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```