R:循环检查文件是否存在并将其放入列表#fail

R: Loop to check if file exists and take it to a list #fail

我有 735 个文件夹,其中一些文件夹中有 .grd 文件,其他文件夹中没有。 在堆栈中进行大量研究后,我想出了一个代码来检查 .grd 文件是否存在,如果存在,则将 .grd 读入列表,如果不存在,则跳过它。但它不起作用......代码生成了一个包含 735 个对象的列表,其中一些是空的。这是我的代码:

#the folder where all folders are
dir_maxent_spp<-"C:\Users\thai\Documents\ORCHIDACEAE\Ecologicos\w2\SpDistModel\Maxent_spp_20170815\xm"

#list all folders within 
files <- list.files()

#create an empty list to receive the reads
grd_list<-list()

for (i in 1:length(files)){

#get into each folder
setwd(paste(dir_maxent_spp,"\",files[i], sep="")) 

#set the name of the file I'm looking for
f <- paste0(paste(gsub('\s+','_',files[i]),"_pred.grd", sep=""))

#check it's existence and it does exist, get it to the list
if (file.exists(f))
grd_list[[i]]<-stack(f)
}

现在,我意识到问题出在这部分:grd_list[[i]]<-stack(f) ...在这里我将 .grd 放到了列表的第 i 个位置,对吗?但是如何在不跳过列表中的位置的情况下跳过 i 的值?我是R的新手,如果问题太幼稚,我很抱歉

一种方法是使用另一个计数器:

#the folder where all folders are
dir_maxent_spp<-"C:\Users\thai\Documents\ORCHIDACEAE\Ecologicos\w2\SpDistModel\Maxent_spp_20170815\xm"

#list all folders within 
files <- list.files()

#create an empty list to receive the reads
grd_list<-list()

# Loop counter
j <- 1

for (i in files){
  #get into each folder
  setwd(paste(dir_maxent_spp,"\",i, sep="")) 

  #set the name of the file I'm looking for
  f <- paste0(paste(gsub('\s+','_',i),"_pred.grd", sep=""))

  #check it's existence and it does exist, get it to the list
  if (file.exists(f)) {
    # Store stack
    grd_list[[j]]<-stack(f)

    # Increment loop counter
    j <- j + 1
  }
}

您可以Reduce您的列表,它会跳过空行

可重现的例子

grd_list<-list()

grd_list[[3]] <- 3
grd_list[[6]] <- 4

option <- Reduce(rbind, grd_list)

输出

     [,1]
[1,]    3
[2,]    4

@Lyngbakr 的回答让我自己找到了解决方案:

使用

  grd_list[[(legth(grd_list)+1)]]<-stack(f)

而不是

  grd_list[[i]]<-stack(f)