如何从R中各个子文件夹中包含的文件堆叠单个栅格图层?

时间:2018-05-31 15:51:11

标签: r file loops directory raster

我正在使用栅格图层。我在父文件夹中有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.的新人。谢谢!

2 个答案:

答案 0 :(得分:2)

您通常应该使用列表来处理此类事情。您可以将每个堆栈添加为循环中的列表元素。

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)

答案 1 :(得分:1)

如果您愿意,可以使用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))
})