Search code examples
rfor-loopworking-directory

R create new folders in a loop


I have 10 raster files. What I am trying to do is this:

1) Read the first raster in R (a raster file)

2) save that file in a folder (create the folder within the loop)

3) read the second raster file again

4) save that file in a new folder (also created within the loop)

5) keep repeating 10 times

Here is what I manage to do:

for (i in 1:10){
    dir.create(paste0("Run",i))      #this creates a new folder called Run[i] where I will save the raster
    setwd(paste0("Run",i))           # this makes the Run[i] my working directory so that my first raster is saved in Run[i]
    moist<-raster(paste0("R://moist_tif/ind_moist",i,".tif"))      # this reads in my raster moist[i]
    writeRaster(moist,"moist.tif")    # this saves my raster  in folder Run[i]

As you might notice when the loop moves to i+1, the new folder Run[i+1] is created within Run[i] which I do not want. I want to create separate folder for Run[i+1] rather than folders within folders. Hope I wrote the question clearly. Thank you for your help.

Regards


Solution

  • It's your logic. If you change directories, you also need to change back.

    Here is an improved version:

    for (i in 1:10) {
        newdir <- paste0("Run",i)
        dir.create(newdir)      # should test for error
        cwd <- getwd()          # CURRENT dir
        setwd(newdir) 
        moist<-raster(paste0("R://moist_tif/ind_moist",i,".tif"))  
        writeRaster(moist,"moist.tif") 
        setwd(cwd)
    }