R在循环中创建新文件夹

89_*_*ple 2 for-loop r working-directory

我有10个光栅文件.我想要做的是这样的:

1)读取R中的第一个栅格(光栅文件)

2)将该文件保存在文件夹中(在循环中创建文件夹)

3)再次读取第二个光栅文件

4)将该文件保存在新文件夹中(也在循环中创建)

5)不断重复10次

这是我设法做的:

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]
Run Code Online (Sandbox Code Playgroud)

正如您可能注意到循环移动到的那样i+1,Run[i+1]创建了Run[i]我不想要的新文件夹.我想为文件夹中的文件夹Run[i+1]而不是文件夹创建单独的文件夹.希望我能清楚地写出这个问题.谢谢您的帮助.

问候

Dir*_*tel 6

这是你的逻辑.如果更改目录,还需要更改.

这是一个改进版本:

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)
}
Run Code Online (Sandbox Code Playgroud)