Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stacking an existing RasterStack multiple times

My question is pretty similar to an unfortunately unanswered issue recently posted on Stackoverflow. I am dealing with a RasterStack object consisting of twelve layers (one for each month of the year), and I would like to replicate the layers ten times, ending up with a RasterStack consisting of 120 layers, with every 12th layer being similar (i.e., layer 1 is the same like layer 13 is the same like layer 25 and so on).

For replication purposes, let's take an example from the raster package:

library(raster)

file <- system.file("external/test.grd", package = "raster")
s <- stack(file, file, file, file, file, file, file, file, file, file, file, file)

stack(s, s, s, s, s, s, s, s, s, s)

class       : RasterStack 
dimensions  : 115, 80, 9200, 120  (nrow, ncol, ncell, nlayers)
resolution  : 40, 40  (x, y)
extent      : 178400, 181600, 329400, 334000  (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:28992 +towgs84=565.237,50.0087,465.658,-0.406857,0.350733,-1.87035,4.0812 +proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs 
names       : test.1.1, test.2.1, test.3.1, test.4.1, test.5.1, test.6.1, test.7.1, test.8.1, test.9.1, test.10.1, test.11.1, test.12.1, test.1.2, test.2.2, test.3.2, ... 
min values  :  128.434,  128.434,  128.434,  128.434,  128.434,  128.434,  128.434,  128.434,  128.434,   128.434,   128.434,   128.434,  128.434,  128.434,  128.434, ... 
max values  :  1805.78,  1805.78,  1805.78,  1805.78,  1805.78,  1805.78,  1805.78,  1805.78,  1805.78,   1805.78,   1805.78,   1805.78,  1805.78,  1805.78,  1805.78, ... 

Of course, it could be done manually like in the last line of code, but that seems quite inconvenient to me. Any suggestions on how to achieve my goal in a better way would be highly appreciated!

like image 729
fdetsch Avatar asked Feb 15 '23 03:02

fdetsch


1 Answers

You might like mget here, since it takes a character vector of object names and returns the object, so you can do this:

big.stack <- stack( mget( rep( "s" , 12 ) ) )

nlayers( big.stack )
#[1] 144

Or using replicate() to put them in a list if you don't like using mget(), and then stacking the list as a list of rasterLayers is valid input to stack()...

ll <- replicate( 12 , s )

big.stack2 <- stack( ll )

identical( big.stack , big.stack2 )
#[1] TRUE
like image 82
Simon O'Hanlon Avatar answered Feb 16 '23 17:02

Simon O'Hanlon