Thai Thai - 2 years ago 64
R Question

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

I have 735 folders and some of them will have a .grd file inside, others won't.
After a lot of research here in stack, I came up with a code to check if the .grd file exists and, if it does, read the .grd into a list, if doesn't, skip it. But it isn't working... the code is resulting in a list with 735 objects, some of thm, empty. This is my code:

#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)
}


Now, I do realize that the problem is this part:
grd_list[[i]]<-stack(f)
... here I take the .grd into the i'th position of the list, right? But how do I skip a value for i without skipping the position in the list? I'm new to R, I'm sorry if the question is too naive

Answer Source

One way would be to use another counter:

#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
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download