Search code examples
rrasterr-raster

Merging 2 or more raster stacks in 1 in R


I have 2 (or more) raster stacks. Each one went to diverse processing (any kind of stuff) and both stacks maintained theirs extents and resolutions (as initially, both have same extent and resolution). And now I want to make them one stack, instead of 2. So, I would have a 'merged_stack' that would contain all raster from both (or more) stacks. For example:

#creating some data
m1 = matrix(1,30,30)
m2 = matrix(2,30,30)
ma = matrix(10,30,30)
mb = matrix(20,30,30)

#transforming in raster
r1 = raster(m1)
r2 = raster(m2)
ra = raster(ma)
rb = raster(mb)

#now 2 different stacks
stack1 = stack(r1,r2)
{...} some stuff (like raster name changing, sums, multiplications, etc)
goes with stack1 (this stuff does not change extent or resolution of the rasters)

stacka = stack(ra,rb)
{...} diferent stuff goes with stack2 (same here)

#using 'merge' does not work
merged_stack = merge(stack1,stacka)

Any idea in how this could be made? Thanks.


Solution

  • If they have the same projection, extent and resolution, you can use stack on stacks:

    merged_stack <- stack(stack1, stacka)