Skip to content
Prev 7930 / 29559 Next

Specify merging mode

Thanks Robert,

 From what you showed, I tried to wrap the operations in a generic 
function for my own purpose, but I don't know why, I can only apply some 
functions e.g. a mean function is ok, but not a max function. Could you 
point what's wrong ? What's the better way to apply a function to a 
raster list ? My problem is that I have a variable number of rasters to 
merge.

r <- raster()
r1 <- crop(r, extent(-10, 10, -10, 10))
r2 <- crop(r, extent(0, 20, 0, 20))
r3 <- crop(r, extent(10, 30, 10, 30))

r1[] <- 1:ncell(r1)
r2[] <- 1:ncell(r2)
r3[] <- 1:ncell(r3)

fmerge <- function(rasters, fun, ...){
    ex <- raster(unionExtent(rasters))
    res(ex) <- res(rasters[[1]])
    ex[] <- NA
   
    for( i in 1:length(rasters) )
        rasters[[i]] <- merge(rasters[[i]], ex)
   
    do.call( fun, c(rasters, ...) )
}

rfm <- fmerge(rasters, mean, na.rm=T)  #ok
rfx <- fmerge(rasters, max, na.rm=T)   #wrong

Etienne

Robert J. Hijmans wrote :