[Rd] about class(<raster>)

Hervé Pagès hp@ge@@on@g|thub @end|ng |rom gm@||@com
Wed Sep 24 20:56:53 CEST 2025


Hi,

A few years ago, class() on a matrix was modified to return c("matrix", 
"array") instead of just "matrix", thus formalizing the fact that a 
matrix is an array. Concretely this change meant that is.array(), 
inherits() and is() were finally in agreement:

     > is.array(matrix())
     [1] TRUE
     > inherits(matrix(), "array")  # used to return FALSE
     [1] TRUE
     > is(matrix(), "array")  # also used to return FALSE
     [1] TRUE

Has the same kind of change be considered for raster objects? A raster 
object is a matrix, and this is acknowledged by is.matrix() but not by 
inherits() or is():

     > r <- as.raster(array(runif(60), 5:3))
     > is.matrix(r)
     [1] TRUE
     > inherits(r, "matrix")
     [1] FALSE
     > is(r, "matrix")
     [1] FALSE

This is because class(r) only returns "raster":

     > class(r)
     [1] "raster"

Also, because of this, 'r' is not considered an array in a consistent 
manner either:

     > is.array(r)
     [1] TRUE
     > inherits(r, "array")
     [1] FALSE
     > is(r, "array")
     [1] FALSE

These issues would go away if class(r) was returning c("raster", 
"matrix", "array") instead of just "raster":

     > class(r) <- c("raster", "matrix", "array")
     > inherits(r, "matrix")
     [1] TRUE
     > is(r, "matrix")
     [1] TRUE
     > inherits(r, "array")
     [1] TRUE
     > is(r, "array")
     [1] TRUE

Has this been considered?

I'm aware that this kind of change has the potential to be quite 
disruptive because it would break any code around that uses things like

     if (class(r) == "raster") ...

instead of

     if (is.raster(r)) ...

or

     if (inherits(r, "raster")) ...

But consistency is priceless isn't it?

Thanks,

H.

-- 
Hervé Pagès

Bioconductor Core Team
hpages.on.github using gmail.com



More information about the R-devel mailing list