问题
I am working with raster layers. I have 10 subfolders in a parent folder. Each of the subfolders contains hundreds of raster. I would like to apply a script for each of the subfolders and to create several stacks for each of my subfolders.
#List all my subfolders in my parent folder
list_dirs<- list.dirs(path/parentfolder/, recursive = F)
for (i in list_dir){
# set the working directory to the subfolder i
setwd(i)
# List all the files with a certain pattern in the subfolder i
s<- list.files(path=setwd(i), pattern = "cool", recursive=F)
# I do not see how I can create a stack for each of my subfolders here.
#I should have an index i somewhere in the last line.
ss<- stack(s)
}
As a final output, I would like to have 10 stacks corresponding to each of my 10 subfolders. I am new in R. Thanks!
回答1:
You should typically use lists for this kind of thing. You can add each stack as a list element in the loop.
stack.list <- list()
for (i in 1:length(list_dirs)){
s <- list.files(path=list_dirs[i], pattern = "cool", recursive=F, full.names = TRUE)
stack.list[[i]] <- stack(s)
}
Or, slightly better if you want to keep track of which list element corresponds to which folder, you can use:
stack.list[[basename(list_dirs)[i]]] <- stack(s)
回答2:
A lapply
option if you prefer, but really just a different version of dww's answer:
list_dirs <- list.dirs("path/parentfolder/", recursive = F)
names(list_dirs) <- basename(list_dirs)
raster.list <- lapply(list_dirs, function(dir) {
stack(list.files(dir, pattern = "cool", full.names = T, recursive = F))
})
来源:https://stackoverflow.com/questions/50628255/how-to-stack-individual-raster-layers-from-files-contained-in-individual-subfold