Home calcul of the mean of every 6 rasters layer and name of this files
Reply: 1

calcul of the mean of every 6 rasters layer and name of this files

LMontef Published in 2018-02-12 21:10:45Z

I have 28 rasters files combined in a folder. I would like to do the mean of the 3 first rasters, then the mean of the 3 other raster, etc. Then, I should obtain 9 rasters. I would like to name them according to the month. I would like my first raster layer would be named Tmin-2010-01-15, my second one 'Tmin-2010-02-15', ..., and my last and nine raster called 'Tmin-2010-09-15'. I wrote the following code.I do not have any error message but I cannot see any results so I do not know if the logic of the code is good and how to process.

Thanks for any help!

setwd("/Users/lisemontefiore/Documents/Data/Climate Data/test2") 

I stacked my rasters

bands <-list.files(path="xxx",pattern="*.tif",full.names=TRUE)
data_stack <- stack(bands) 

I define the parameters n=number of raster layers, m=number of rasters I want to gather to do the mean

n<- 28
group3=groupn(28, 3)
f=function(v){tapply(v, group3, mean)}
b=calc(data_stack, f)

I define the name of my files created by the function and write the rasters

    months<- seq(from=as.Date("2010-01-15"),
                 to= as.Date("2010-09-15"),
    for (i in seq_along(months))
         {writeRaster <- file.path("b", 
                                   paste('Tmin',months[i], sep=''),
RobertH Reply to 2018-02-12 23:11:02Z

Instead of calc, you can do:

 b <- stackApply(b, group3, mean)

But there is no output because you do not call writeRaster You need something like this:

months <- seq(from=as.Date("2010-01-15"), to= as.Date("2010-09-15"), by='month')
ff <- paste0('Tmin', months, '.tif')

for (i in seq_along(months)) {
    writeRaster(b[[i]]], ff[[i]])
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.366269 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO