1

I have a large time series (> 2000 files), but as example, I am going to use just a list of 10 tif files:

> # list of tif files
> setwd("...raster/daily/")
> l <- list.files(getwd(), pattern=".tif")

I get this result:

> l
> [1] "ws_1.tif"  "ws_10.tif" "ws_2.tif"  "ws_3.tif"  "ws_4.tif"  "ws_5.tif"  "ws_6.tif"  "ws_7.tif"  "ws_8.tif"  "ws_9.tif

I need to change each filemame to something like this:

new_Year-Month-Day.tif

new_2009-01-01.tif

new_2009-01-02.tif

new_2009-01-03.tif

...

I am trying to do this with the command below, but without success:

# command for to rewrite the set of raster files with the new filenames
for (i in 1:length(l)){
  r <- raster(l[i])
  tempo <- seq(as.Date("2009/01/02"), by = "day", length.out = 10)
  filename = paste0("new_",tempo)
  writeRaster(r, extension(filename, 'tif'))
}

When I use this command, the R just create the first file (new_2009-01-01.tif) and return the following error:

Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  : 
  Cannot create a RasterLayer object from this file.
In addition: There were 22 warnings (use warnings() to see them)

I already tried to use other commands like stack and brick the raster files, names to set the new names, but still unsuccessful.

Does anyone know how to do this or at least point me another way to solve this problem?

Thanks!

  • possible duplicate of https://stackoverflow.com/questions/10758965/how-do-i-rename-files-using-r – raninjan Sep 05 '17 at 17:32
  • 1
    you can use `file.rename(l,filename)` in your code above. You don't need the loop `from(i in 1:length(l))` – raninjan Sep 05 '17 at 17:33
  • @raninjan, thank you! It worked. So, to solve my problem I used: `l <- list.files(getwd(), pattern=".tif") tempo <- seq(as.Date("2009/01/01"), by = "day", length.out = 10) filename = paste0("new_",tempo,".tif") file.rename(l,filename)` – João dos Reis Sep 05 '17 at 17:48
  • that's great! Glad it helped :) – raninjan Sep 05 '17 at 17:55

0 Answers0