Search code examples
rraster

How to rename file name as another file name?


I have raster data files for certain dates at a gap of few days such as 20200110.tif, 20200115.tif, 20200310.tif, 20200315.tif and so on. After running few algorithms (mentioned below) on input files, I am getting the output files as x1.tif, x2.tif.... whereas I want them similar to be the input file names. How to achieve that? Also, I am getting the output in C drive. I need to know where I can define the output directory in the code?

library(terra)
f <- list.files(path="F:/Data/", pattern=".tiff$", full.names=TRUE)
r <- rast(f)
t <- clamp(r, 50, 750, values=FALSE)
x <- 1/10000 * t + 0             
outnames <- paste0("x", 1:nlyr(x), ".tif")
writeRaster(x, outnames)
outnames

I am getting output raster files as x1, x2...and in C directory whereas I want output file names similar to inputfile names and in an output directory e.g. F:/Data/Out. I referred to various answers and tried file.rename, gsub, substr functions but as I am novice to R, I am not able to write the code properly and get the desired output.


Solution

  • If you get the file names without full.names = TRUE, you can use them for both reading and saving, specifying different directories:

    library(terra)
    
    data_dir <- "F:/Data/"
    f <- list.files(path = data_dir, pattern = ".tiff$")
    readnames <- paste0(data_dir, f)
    r <- rast(readnames)
    t <- clamp(r, 50, 750, values=FALSE)
    x <- 1/10000 * t + 0             
    outnames <- paste0(data_dir, "Out/", f)
    writeRaster(x, outnames)