我有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]

您可能会注意到,当循环移至i+1时,在我不需要的Run[i+1]中创建了新文件夹Run[i]。我想为Run[i+1]创建单独的文件夹,而不是文件夹中的文件夹。希望我清楚地写了这个问题。感谢您的帮助。

问候

最佳答案

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

这是一个改进的版本:

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

10-01 15:51
查看更多