Michael_Brun
Michael_Brun

Reputation: 51

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.

Upvotes: 0

Views: 109

Answers (2)

zephryl
zephryl

Reputation: 17234

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)

Upvotes: 1

Yama
Yama

Reputation: 98

You can define the output path by passing it through the filename as path/to/file instead of just file.

For the filenames: your outnames is built upon the string "x" to which you add a number and the extension .tif. This is why your files a renamed x.tif. Reusing the object f should do the trick:

writeRaster(x, f)

But you might get a warning or an error because the files already exist.

Upvotes: 1

Related Questions