Pergunta

I want to write many raster files using a for loop.

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

How do I create for each file a new folder within "D:/FolderA/FolderB/FolderC/FolderD/mosaics/" which includes FolderE1/, E2/... etc. plus the filename, e.g. mosaic.tif ?

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

Does not give a satisfying result.

Foi útil?

Solução

Just to demonstrate one method of making folders within a loop: If you have the directories in an object just looping over the elements of that object.

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 
}

Just a warning: this is all a bit dangerous because mistakes can make a big mess.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top