Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R在循环中创建新文件夹_R_For Loop_Working Directory - Fatal编程技术网

R在循环中创建新文件夹

R在循环中创建新文件夹,r,for-loop,working-directory,R,For Loop,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

我有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]
for(1:10中的i){
dir.create(粘贴0(“Run”,i))#这将创建一个名为Run[i]的新文件夹,我将在其中保存光栅
setwd(paste0(“Run”,i))#这使Run[i]成为我的工作目录,以便我的第一个光栅保存在Run[i]中

这是你的逻辑。如果你更改目录,你也需要重新更改

以下是一个改进的版本:

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)
}
for(1:10中的i){

newdir(未完成/未测试)我认为您需要类似于
setwd(paste0(“../Run”,I))的东西
--虽然您在第一次循环时必须小心,因为此时您不在子目录中…但问题的存在是因为您更改了工作目录。根据您的系统,您可以尝试类似于
dir.create(sprintf(“.\\run%i\\”,i))
的操作。