Search code examples
rloopsrastersubdirectorybatch-rename

Loop through multiple folder and Calculate mean of raster of Same folder R


I am looking to loop through different subfolders in a parent folder in R. I precise that I am a new user of R. I have 10 subfolders that are in 1 parent folder. Each of the subfolders contains 100 rasters files. For each of the subfolder I would like to calculate the mean of all the raster files and write the new raster based on the name of the subfolder and add the description "mean".

             |--Subfol i=1 --[raster(j=1), 
             |                 raster(j),    --mean 100 files -- Subfol1mean.        |
             |                raster(j=100)]
             |
parent_fold--|
             |
             |----Subfol i=1 --[raster(j=1),
                                raster(j),    --mean 100 files -- Subfol10mean.
                                raster(j=100)]

I tried the following code to start:

 setwd("XXXX/parent_fold")
#list all the files in the subfolders
sub<- list.files(full.names = F , recursive =F, pattern='tiff')
for(j in 1:length(sub)){
h<- list.files(path=sub[j], recursive = T, full.names = T,    pattern='tiff')
d<-stack(h)
x<-stackApply(d, mean)
#writeRaster
}

I have some difficulties to pursue and I am not sure what I did I the correct path. Thanks for any help.

I got the following error:

 Error in (function (classes, fdef, mtable)  : 
 unable to find an inherited method for function ‘nlayers’ for   signature ‘"matrix"’

Solution

  • Below a solution that works well: 
    
    setwd("XXX/parent_fold")
    library(raster)
    sub <- list.dirs(full.names=FALSE, recursive=FALSE)
    
    for(j in 1:length(sub)) {
    print(sub[j])
    
    h <- list.files(path=sub[j], recursive=TRUE, full.names=TRUE,  pattern='.tiff')
    print(h)
    
    d <- stack(h)
    mean <- stackApply(d, indices =  rep(1,nlayers(d)), fun = "mean", na.rm = T)
    
    writeRaster(mean, filename=paste0(sub[j], "_mean.tif"), overwrite=TRUE)
    }