代码之家  ›  专栏  ›  技术社区  ›  Thai

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

  •  0
  • Thai  · 技术社区  · 7 年前

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

    #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新手,如果这个问题太天真,我很抱歉

    3 回复  |  直到 7 年前
        1
  •  3
  •   Dan    7 年前

    #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
      }
    }
    
        2
  •  1
  •   CPak    7 年前

    Reduce 您的列表,将跳过空行

    可复制示例

    grd_list<-list()
    
    grd_list[[3]] <- 3
    grd_list[[6]] <- 4
    
    option <- Reduce(rbind, grd_list)
    

         [,1]
    [1,]    3
    [2,]    4
    
        3
  •  0
  •   Thai    7 年前

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

    使用

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

    而不是

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