[GIS] combine rasters into single raster with multiple field values in R

rraster

I have several raster brick objects that I would like to combine into one raster with multiple field values for each cell, but I am not sure how to do this in R.

For example, let's say I have two layers in a 2*2 raster brick.

r <-raster(nrow=2,ncol=2)
r[] <- round(runif(ncell(r))* 10,0)
s <-raster(nrow=2,ncol=2)
s[] <- round(runif(ncell(r))* 10,0)
t = brick(r,s)

I would like to combine the values for r and s into a single raster with multiple values (at the object@data@attributes slot, I think) associated with each cell.

So, in the above example, if cell 1 = 1 in r and cell 1 = 2 in s, then the output that I desire is that the resulting raster contain two fields at @data@attributes, the first field = 1 and the second field = 2.

Best Answer

If you would like to keep the object type(s) as raster I would take a look at the ratify function although, I do not think that it is intended for numeric data.

require(raster)
r2 <- raster(nrow=10, ncol=10)
  r2[] = 1
    r2[51:100] = 2
      r2[3:6, 1:5] = 3

r2 <- ratify(r2)
  rat <- levels(r2)[[1]]
    rat$MyRATValue <- c(100,200,300)
      rat$code <- c(1,2,3)
        levels(r2) <- rat
          r2

You could also coerce the raster brick object to a SpatialPixelsDataFrame object where the @data slots holds attributes for each raster. This is however, not necessarily memory safe.

require(raster)
r <-raster(nrow=2,ncol=2)
  r[] <- round(runif(ncell(r))* 10,0)
  s <-raster(nrow=2,ncol=2)
    s[] <- round(runif(ncell(r))* 10,0)
      r = brick(r,s)

r <- as(r, "SpatialPixelsDataFrame")
  str(r@data)
    head(r@data)