I have a list of file names that encode some information as a time stamp. I would like to replace the time stamp with the appropriate corresponding information, while retaining the rest of the filename.
library(tidyverse)
filenames = c("Depth (01OCT2025 02 00 00).Terrain_2022_PartLevee.Inputs.tif", "Depth (01OCT2025 03 00 00).Terrain_2022_PartLevee.Inputs.tif", "Shear Stress (01OCT2025 02 00 00).Terrain_2022_PartLevee.Inputs.tif", "Shear Stress (01OCT2025 10 00 00).Terrain_2022_PartLevee.Inputs.tif", "Velocity (01OCT2025 02 00 00).Terrain_2022_PartLevee.Inputs.tif", "Velocity (01OCT2025 06 00 00).Terrain_2022_PartLevee.Inputs.tif" )
from = c("(01OCT2025 02 00 00)",
"(01OCT2025 06 00 00)",
"(01OCT2025 10 00 00)",
"(01OCT2025 14 00 00)"
)
to = c("Q2_ 1960cfs",
"Q10_ 4440cfs",
"Q20_ 5150cfs",
"Q100_ 7130cfs"
)
key = tibble(from, to)
# A tibble: 4 × 2
from to
<chr> <chr>
1 (01OCT2025 02 00 00) Q2_ 1960cfs
2 (01OCT2025 06 00 00) Q10_ 4440cfs
3 (01OCT2025 10 00 00) Q20_ 5150cfs
4 (01OCT2025 14 00 00) Q100_ 7130cfs
I am looking to do something along the lines of:
str_replace_all(filenames, from, to) # doesn't work
to end up with:
[1] "Depth Q2_ 1960cfs.Terrain_2022_PartLevee.Inputs.tif"
[2] "Depth (01OCT2025 03 00 00).Terrain_2022_PartLevee.Inputs.tif" ## Not in lookup table
[3] "Shear Stress Q2_ 1960cfs.Terrain_2022_PartLevee.Inputs.tif"
[4] "Shear Stress Q20_ 5150cfs.Terrain_2022_PartLevee.Inputs.tif"
[5] "Velocity Q2_ 1960cfs.Terrain_2022_PartLevee.Inputs.tif"
[6] "Velocity Q10_ 4440cfs.Terrain_2022_PartLevee.Inputs.tif"
I could pull the filename vector into a table, split the string into components, left_join() with the replacement table, and recombine back into a file name, but seems like a bit cumbersome.