Skip to content

Coercing multiband readGDAL objects to a matrix/vector...

3 messages · Jonathan Greenberg, Michael Sumner

#
Michael:

    Thank you for your prompt reply -- if I wanted to extract multiple 
bands in a single call, how would I do that?  I suppose I could do it 
with a for-next loop, but it seems there is probably some simple way of 
doing this:

as.matrix(x[1:3]) (doesn't work, but the idea is I want bands 1-3 in this matrix).

--j
Michael Sumner wrote:
#
Can you provide more detail as to what you mean?

If you want more than one band in the matrix you'll need to pre-allocate 
the result and use sub-indexing into that matrix (2D).

In one step you could access the bands from the Spatial*DataFrame 
directly as columns/vectors, but you'd have to handle the orientation 
specially.

Perhaps you actually want the 3 bands as a 3D array?

Here's an example of that.

library(sp)
data(meuse.grid)
m = SpatialPixelsDataFrame(points = meuse.grid[c("x", "y")], data = 
meuse.grid)

dimXY <- getGridTopology(m)@cells.dim  ## the X/Y dimensions of the result

## the 3D result
result <- array(NA, c(dimXY, 3))

## slot each band matrix into the 3D array
for (i in 1:3) {
    result[,,i] <- as.image.SpatialGridDataFrame(m[i])$z
}
## check the result

image(result[,,1])
image(result[,,2])
image(result[,,3])

Regards, Mike.
Jonathan Greenberg wrote: