如何从 R 中各个子文件夹中包含的文件堆叠各个栅格层?
How to stack individual raster layers from files contained in individual subfolders in R?
我正在处理栅格图层。我在父文件夹中有 10 个子文件夹。每个子文件夹都包含数百个光栅。我想为每个子文件夹应用一个脚本,并为我的每个子文件夹创建多个堆栈。
#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 的新手。谢谢!
对于这种事情,您通常应该使用列表。您可以将每个堆栈添加为循环中的列表元素。
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)
}
或者,如果您想跟踪哪个列表元素对应于哪个文件夹,效果会更好一些,您可以使用:
stack.list[[basename(list_dirs)[i]]] <- stack(s)
一个 lapply
选项,如果你愿意,但实际上只是 dww 答案的不同版本:
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))
})
我正在处理栅格图层。我在父文件夹中有 10 个子文件夹。每个子文件夹都包含数百个光栅。我想为每个子文件夹应用一个脚本,并为我的每个子文件夹创建多个堆栈。
#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 的新手。谢谢!
对于这种事情,您通常应该使用列表。您可以将每个堆栈添加为循环中的列表元素。
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)
}
或者,如果您想跟踪哪个列表元素对应于哪个文件夹,效果会更好一些,您可以使用:
stack.list[[basename(list_dirs)[i]]] <- stack(s)
一个 lapply
选项,如果你愿意,但实际上只是 dww 答案的不同版本:
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))
})