Reputation: 33
I am using the raster package to process some raster files/satellite data. I have used the below to select the path and my input image:
inputfile <- choose.files(default = "D:\\March\\NewData\\2017", caption = "Select files",
multi = TRUE, filters = Filters,
index = nrow(Filters))
this gives:
inputfile = D:\\March\\NewData\\2017\\chlorophyll.tiff
To get my processed raster file saved in the same directory and same filename but with an additional word, I have to copy and paste:
D:\\March\\NewData\\2017\\chlorophyll.tiff
in the below (and manually add '_new')
writeRaster(stack_cor, "D:\\March\\NewData\\2017\\chlorophyll_new.tiff", format='GTiff',
As I need to do this repetitively, I'd like to get inputfile
automatically and then just manually add _new
to it - instead of having to copy and paste inputfile
in the output, i.e. writeRaster(........)
each time.
Upvotes: 2
Views: 247
Reputation: 2699
That's what regular expressions are for:
inputfile <- "D:\\March\\NewData\\2017\\chlorophyll.tiff"
outputfile <- gsub("\\.tiff$", "_new.tiff", inputfile)
outputfile
produces:
[1] "D:\\March\\NewData\\2017\\chlorophyll_new.tiff"
Upvotes: 1
Reputation: 160607
fn <- "D:\\March\\NewData\\2017\\chlorophyll.tiff"
paste0(tools::file_path_sans_ext(fn), "_new.", tools::file_ext(fn))
# [1] "D:\\March\\NewData\\2017\\chlorophyll_new.tiff"
(The tools
package is installed with base R, it's just not attached by default.)
Also,
gsub("\\.tiff$", "_new.tiff", fn)
# [1] "D:\\March\\NewData\\2017\\chlorophyll_new.tiff"
If you have a multitude of possible file extensions, then
gsub("\\.(tiff|jpeg|jpg|gif|png|something)$", "_new.tiff", fn)
# [1] "D:\\March\\NewData\\2017\\chlorophyll_new.tiff"
Upvotes: 0