在for循环中生成新的输出文件名

时间:2014-03-06 16:27:21

标签: r for-loop filenames

我想使用for循环编写许多光栅文件。

path <- "D:/FolderA/FolderB/FolderC/FolderD/"
files1 <- c("FolderE1/raster.tif", 
            "FolderE2/raster.tif", 
            "FolderE3/raster.tif")
files2 <- c("FolderF1/raster.tif",
            "FolderF2/raster.tif",
            "FolderF3/raster.tif")


for (i in 1:length(files1)) {
  raster1 <- raster(paste(path, files1[i], sep = ""), band = 1)
  is.na(raster1[[0]])

  raster2 <- raster(paste(path, files2[i], sep = ""), band = 1)
  is.na(raster2[[0]])

  mosaicraster <- mosaic(raster1, raster2, fun = mean)
  NAvalue(mosaicraster) <- 0
  outputfile <- paste(path, "mosaics/", files1[i], sep = "")
  writeRaster(mosaikraster, outputfile , type = "GeoTIFF", datatype = "INT1U", overwrite = TRUE)


  print(c(i, "of", length(files1)))
}

如何为每个文件创建"D:/FolderA/FolderB/FolderC/FolderD/mosaics/"中包含FolderE1/, E2/... etc.加上文件名的新文件夹,例如mosaic.tif

outputfile <- paste(path, "mosaics/", files1[i], sep = "")

不能给出令人满意的结果。

1 个答案:

答案 0 :(得分:1)

只是为了演示一种在循环中创建文件夹的方法:如果对象中的目录只是循环遍历该对象的元素。

folders1 <- c("FolderE1", 
            "FolderE2", 
            "FolderE3")




for(i in folders1)
{
  dir.create(i)              #creates a dir named after the ith element of folders1
  setwd(i)                   #goes into that directory
  tiff('raster.tif')         #plots your picture
  plot(rnorm(10,rnorm(10)))
  dev.off()
  setwd('../')               #goes out to the original folder 
}

只是一个警告:这有点危险,因为错误可能会造成很大的混乱。