From maechler at stat.math.ethz.ch  Tue Feb  1 09:22:03 2011
From: maechler at stat.math.ethz.ch (Martin Maechler)
Date: Tue, 1 Feb 2011 09:22:03 +0100
Subject: [Rd] [.raster bug {was "str() on raster objects fails .."}
In-Reply-To: <AANLkTimycPK-3_mj5OPd0eLauAh41r2-Wkrp7j2jo1sw@mail.gmail.com>
References: <AANLkTimycPK-3_mj5OPd0eLauAh41r2-Wkrp7j2jo1sw@mail.gmail.com>
Message-ID: <19783.49835.494142.88222@stat.math.ethz.ch>

>>>>> Henrik Bengtsson <hb at biostat.ucsf.edu>
>>>>>     on Mon, 31 Jan 2011 11:16:59 -0800 writes:

    > Hi, str() on raster objects fails for certain dimensions.  For
    > example:

    >> str(as.raster(0, nrow=1, ncol=100)) 'raster' chr [1, 1:100]
    > "#000000" "#000000" "#000000" "#000000" ...

    >> str(as.raster(0, nrow=1, ncol=101)) Error in `[.raster`(object,
    > seq_len(max.len)) : subscript out of bounds

    > This seems to do with how str() and "[.raster"() is coded; when
    > subsetting as a vector, which str() relies on, "[.raster"()
    > still returns a matrix-like object, e.g.

    >> img <- as.raster(1:25, max=25, nrow=5, ncol=5);
    >> img[1:2]
    > [,1]      [,2]      [,3]      [,4]      [,5]
    > [1,] "#0A0A0A" "#3D3D3D" "#707070" "#A3A3A3" "#D6D6D6"
    > [2,] "#141414" "#474747" "#7A7A7A" "#ADADAD" "#E0E0E0"

    > compare with:

    >> as.matrix(img)[1:2]
    > [1] "#0A0A0A" "#3D3D3D"


    > The easy but incomplete fix is to do:

    > str.raster <- function(object, ...) {
    > str(as.matrix(object), ...);
    > }

    > Other suggestions?

The informal "raster" class is behaving ``illogical''
in the following sense:

 > r <- as.raster(0, nrow=1, ncol=11)
 > r[seq_along(r)]
 Error in `[.raster`(r, seq_along(r)) : subscript out of bounds

or, here equivalently,
 > r[1:length(r)]
 Error in `[.raster`(r, 1:length(r)) : subscript out of bounds

When classes do behave in such a way, they definitely need their
own str() method.

However, the bug really is in "[.raster":
Currently,  r[i] is equivalent to  r[i,]  which is not at all 
matrix-like and its help clearly says that subsetting should
work as for matrices.
A recent thread on R-help/R-devel has mentioned the fact that
"[" methods for matrix-like methods need to use both nargs() and
missing() and that "[.dataframe" has been the example to follow
"forever", IIRC already in S and S-plus as of 20 years ago.

Thank you, Henrik, for the bug report.
Martin



[Rd] [.raster bug {was "str() on raster objects fails .."}
Martin Maechler