如何从R中各个子文件夹中包含的文件中堆叠各个栅格图层? [英] How to stack individual raster layers from files contained in individual subfolders in R?
问题描述
我正在处理栅格图层。我在父文件夹中有10个子文件夹。每个子文件夹包含数百个栅格。我想为每个子文件夹应用一个脚本,并为每个子文件夹创建几个堆栈。
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)
}
作为最终输出,我希望有10个堆栈分别对应于我的10个子文件夹。我是R新手。谢谢!
As a final output, I would like to have 10 stacks corresponding to each of my 10 subfolders. I am new in R. Thanks!
推荐答案
您通常应使用列表来进行此类操作。您可以在循环中将每个堆栈添加为列表元素。
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)
这篇关于如何从R中各个子文件夹中包含的文件中堆叠各个栅格图层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!