2
votes

I have two sets of rasterstacks (each with a few hundred raster layers) - the first is a rasterstack containing a set of sensored time series images (with gap) and a second stack of temporally interpolated images for the gaps of the first set. Naming of the layers in each set is according to the day they where measured/or interpolated, starting from day 1....n

I now want to combine these two sets into one ordered (from 1 to n according to layer name) rasterstack. I have looked into different ways of doing this but haven't been able to get the results;

  • A way to order the layers within a rasterstack (for example by using something like this (comb_r is the raster stack from my reproducible example below). This reorders the names but not the entire layers:

    names(comb_r)<-comb_r[order(names(comb_r))]
    
  • create two lists of layers in both stacks using the unstack function and than create a combined ordered list as an input to a new stack operation (did not get this to work).

  • finally I guess I could save all layers onto the hard disk and than reassemble a stack from there (considering the many layers probably not the best way forward).

Any suggestions on how to proceed would be welcome. I have added a toy example of my problem here:

library(raster)

r1 <- raster(matrix(runif(9), ncol = 3))
r2 <- raster(matrix(runif(9), ncol = 3))
r3 <- raster(matrix(runif(9), ncol = 3))
r4 <- raster(matrix(runif(9), ncol = 3))
r5 <- raster(matrix(runif(9), ncol = 3))

r <- stack(r1, r2, r3,r4,r5)
names(r)<-c(1,4,6,8,10)

r6 <- raster(matrix(runif(9), ncol = 3))
r7 <- raster(matrix(runif(9), ncol = 3))
r8 <- raster(matrix(runif(9), ncol = 3))
r9 <- raster(matrix(runif(9), ncol = 3))
r10 <- raster(matrix(runif(9), ncol = 3))

    rr <- stack(r6,r7,r8,r9,r10)

names(rr)<-c(2,3,5,7,9)

comb_r<-stack(r,rr)
4

4 Answers

6
votes

Can you not just take a 'subset' in a different order:

subset(comb_r, order(c(1,4,6,8,10,2,3,5,7,9)))

You can choose the second argument of 'subset' to reflect your desired ordering - the one you've given is slightly odd, in that it takes one from r, then two from rr, then alternates from r and rr.

0
votes

This should works:

ReorderStack<- stack(comb_r[[1]],comb_r[[4]],comb_r[[6]],comb_r[[8]],comb_r[[10]],
                    comb_r[[2]], comb_r[[3]],comb_r[[5]],comb_r[[7]],comb_r[[9]])
0
votes

Calling order within the subset function did not work for me. I used the following:

subset(comb_r, c(1,4,6,8,10,2,3,5,7,9))
0
votes

If your rasters are already named you can just order them like so:

ordered_names <- c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
ordered_stack <- comb_r[[ordered_names]]