Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge rasters of different extents, sum overlapping cell values in R

I am trying to merge rasterized polylines which have differing extents, in order to create a single surface indicating the number of times cells overlap.

Due to computational constraints (given the size of my study area), I am unable to use extend and then stack for each raster (total count = 67).

I have come across the merge function in R, and this allows me to merge rasters together into one surface. It doesn't, however, seem to like me inserting a function to compute the sum of overlapping cells.

Maybe I'm missing something obvious, or this is a limitation of the merge function. Any advice on how to generate this output, avoiding extend & stack would be greatly appreciated!

Code:

# read in specific route rasters
raster_list <- list.files('Data/Raw/tracks/rasterized/', full.names = TRUE)

for(i in 1:length(raster_list)){

   # get file name
   file_name <- raster_list[i]

   # read raster in
   road_rast_i <- raster(file_name)

   if(i == 1){

   combined_raster <- road_rast_i

   } else {

   # merge rasters and calc overlap
   combined_raster <- merge(combined_raster, road_rast_i, 
                            fun = function(x, y){sum(x@data@values, y@data@values)})
  }
 }

Image of current output:

Image of current output

Image of a single route (example):

Image of a single route (example)

Image of fix:

Image of fix)

like image 620
SpatialProgramming Avatar asked Jun 07 '18 11:06

SpatialProgramming


People also ask

Can you merge rasters?

The Merge Rasters function represents a grouped or merged collection of rasters. It is useful when you have multiple rasters that you want treated as a single item, for example, to calculate the same statistics for all, or to treat as one image when color balancing (thereby, not color balancing each image separately).


1 Answers

Solved. There's a mosaic function, which allows the following:

combined_raster <- mosaic(combined_raster, road_rast_i, fun = sum)
like image 125
SpatialProgramming Avatar answered Sep 18 '22 01:09

SpatialProgramming