Skip to content
Prev 7237 / 29559 Next

Overlay-ing two grids

Dear all,

I have two "nested" grids (SpatialGridDataFrame) looking like this:

prj <- "+proj=utm +zone=28 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
gt1 <- GridTopology(c(5, 5), c(10, 10), c(100, 100))
gt2 <- GridTopology(c(50, 50), c(100, 100), c(10, 10))
band1 <- sample(c(0, 1), replace = TRUE, size = 10000)
sgdf1 <- SpatialGridDataFrame(gt1, data.frame(band1), CRS(prj))
sgdf2 <- SpatialGridDataFrame(gt2, data.frame(band1=rep(0, 100)), CRS(prj))
## Graphic display
spplot(sgdf1, scales = list(draw = TRUE),
        panel = function(...){
            panel.gridplot(...)
            sp.grid(sgdf2, col = 0)
            })

I want to compute the mean (and other statistics) of sgdf1 at data$band1 
according to the cells defined in sgdf2. How can I do that ? I tried to 
use overlay, without success:

 > sgdf3 <- overlay(sgdf1, sgdf2, fn = mean)
 > sgdf3 at data$band1
   [1] 1 0 0 0 0 0 1 1 1 0 0 1 0 0 0 0 0 1 1 0 1 0 1 1 0 1 0 0 0 0
  [31] 0 0 1 0 1 1 1 0 0 0 0 0 0 1 0 1 1 0 0 0 1 0 1 0 1 0 1 1 0 0
  [61] 1 1 0 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0
  [91] 1 0 1 1 1 0 1 0 1 0

All the best,

Renaud