Search code examples
rsubdirectory

Within a loop how can I change directories that have a specific name?


I assign the name of the species in a vector

sp1 <- Basper

to directly access the files for example:

occ_sp1 <- read.table (paste ("H: / Botrops_p /", sp1, '. txt', sep = ""), 
                       header = TRUE, sep = "\ t")

all.species <-list.files("H:/Sim_crotalus/Crota.puntos.pam",pattern=".txt")
sp.names <- gsub(".txt","",all.species)
sp.combn <- combn(sp.names,2)
sp.combn 

resul <- matrix(nrow=406,ncol=7,byrow=TRUE)
colnames(resul) <- c("D1","D2","p.D1","p.D2")

  for(i in 1:ncol(sp.combn)){
  print(i)
  sp1 <- sp.combn[1,i]
  sp2 <- sp.combn[2,i]
  
  occ_sp1 <- read.table(paste("H:/E_Crotalus/par1/",sp1,'.txt',sep = ""), header=TRUE,sep="\t")
occ_sp2 <- read.table(paste("H:/E_Crotalus/par1/",sp2,'.txt',sep = ""), header=TRUE,sep="\t")

clim2 <- stack(list.files(path="H:/Crotalus_pam/M2/Caqui", pattern='.asc',full.names = TRUE))

w I need to access folders(subdirectories) that have the same name of sp1 to stack the raster files that I have tried

setwd ("H: / Botrops_p / Basper")

clim2 <- stack (list.files (pattern = '. asc', full.names = TRUE))

there is some way to avoid putting the name of the folder in setwd() and relating it to the assigned sp1 in the beginning

Trying to be a little clearer about the problem I put a broader example of my code

I have a list of species and I will make combinations of pairs of species in the case of txt files, no problem because I assign the name of the file to the vector sp1 <- Catrox

But in the case of the .asc they are different folders that have the same name of sp1 for example in this case Catrox and they contain 6 raster each one

In this case I would have to manually change the name Caqui

There is some way to recognize the folder as the file with the same name


Solution

  • Finally! My interests in snakes and R have crossed over!

    Without seeing the structure of your directories and files on disk, it's difficult to figure out exactly what you need to do, but something along these lines might help:

    # If sp1 is 'Caqui', this will return the paths of all .asc files
    #   in the 'H:/Crotalus_pam/M2/Caqui/' directory:
    thisDir <- paste("H:/Crotalus_pam/M2/", sp1, sep="")
    clim2 <- stack(list.files(path=thisDir, pattern='.asc', full.names=TRUE))
    

    If you're still having issues, please update your question with more details (especially details of how your files and directories are organised).