[R] zero-offset matrices

Martyn Plummer plummer at iarc.fr
Tue Mar 2 15:54:26 CET 1999


Jonathan Rougier wrote:
> 
> Has anyone written subscripting methods for matrices which are indexed
> from zero? i.e. functions such as "[.zoffset" and "[<-.zoffset" which
> would allow, given an appropriate function "zmatrix"
> 
> "zmatrix" <- function(...)
> {
>         robj <- matrix(...)
>         class(robj) <- "zoffset"
>         robj
> }
> 
> fred <- zmatrix(1:20, 4, 5)
> fred[0, 4]              # would be 17
> fred[3, ] <- NA         # would set the last row to NA

No, but it's not hard. 

"[.zoffset" <- function (x, i, j, drop = FALSE) 
{
            if (!missing(i) && is.numeric(i)) {
                    if (any(i < 0)) 
                            stop("negative subscripts forbidden")
                    else i <- i + 1
            }
            if (!missing(j) && is.numeric(j)) {
                    if (any(j < 0)) 
                            stop("negative subscripts forbidden")
                    else j <- j + 1
            }
            y <- NextMethod("[", x)
            if (is.matrix(y)) 
                    class(y) <- "zoffset"
            return(y)
}

"[<-.zoffset" <- function (x, i, j, value) 
{
	    if (!missing(i) && is.numeric(i)) {
	    	    if (any(i < 0)) 
	    	    	    stop("negative subscripts forbidden")
	    	    else i <- i + 1
	    }
	    if (!missing(j) && is.numeric(j)) {
	    	    if (any(j < 0)) 
	    	    	    stop("negative subscripts forbidden")
	    	    else j <- j + 1
	    }
	    y <- unclass(x)
	    if (missing(i) && missing(j)) 
	    	    y[, ] <- value
	    else if (missing(i)) 
	    	    y[, j] <- value
	    else if (missing(j)) 
	    	    y[i, ] <- value
	    else y[i, j] <- value
	    if (is.matrix(y)) 
	    	    class(y) <- class(x)
	    y
}

You might prefer to call your new class "zmatrix", since this matches the
function that creates it, and you will probably want to define "zvector"
as well.

The idea that subscripts start from 1 in R is pretty fundamental, and you
may be entering a world of pain by messing with it.

YMMV
Martyn
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list