Reputation: 3
I have a folder that contains about 140 .tif files. I need to remove the '[]' from the end of each file name.
For example, I have a file named "GOGA_na_MP_FortBakerTopography_196[].tif" and need it to be renamed to "GOGA_na_MP_FortBakerTopography_196.tif".
I have tried the following using a for loop to iterate through all files and gsub to remove the brackets in replace of nothing.
raster_files <- list.files(pattern =".tif$", full.names = TRUE)
for (files in raster_files){
raster_name <- basename(files)
file_name <- gsub("[", "", gsub("]", "", raster_name, fixed = TRUE), fixed = TRUE)
}
I have read through all the other stack questions that are similar to this (inlcuding Removing brackets) and tried to implement their solutions and have had no success. Any help is greatly appreciated thank you.
EDIT EDIT PART 2
Thank you for support on this. I am new to this and I appreciate the patience.
I have figured the code out and have it working when I print out the file names. However, I cannot seem to figure out how to overwrite the name of the files within my FileExplorer and not just within RStudio. The files in the explorer are not renamed but they show up correctly when printed to the console in R.
Example code:
raster_files <- list.files(pattern =".tif$", full.names = TRUE)
file_name = character(length(raster_files))
file_name
for (i in seq_along(raster_files)){
raster_names <- basename(raster_files[i])
file_name[i] <- gsub("[]", "", raster_names, fixed = TRUE)
print(file_name[i])
}
Upvotes: 0
Views: 96
Reputation: 146070
Your gsub
code is fine (could be improved, but it should work). The issue is your loop. You are overwriting file_name
at every iteration. You could fix your loop like this:
## works, but slow and over-complicated
file_name = character(length(raster_files))
for (i in seq_along(raster_files)){
raster_name <- basename(raster_files[i])
file_name[i] <- gsub("[", "", gsub("]", "", raster_name, fixed = TRUE), fixed = TRUE)
}
Note how we use file_name[i]
above, so that we're assigning to a different element of file_name
at each loop iteration.
However, the functions basename
and gsub
are vectorized so looping just makes your code more complicated and less efficient. We can use the vectorization to work on the who raster_files
vector at once:
## better
raster_names <- basename(raster_files)
file_name <- gsub("[", "", gsub("]", "", raster_names, fixed = TRUE), fixed = TRUE)
But we can do better still - gsub
isn't limited to one bracket at a time:
## much better
raster_names <- basename(raster_files)
file_name <- gsub("[]", "", raster_names, fixed = TRUE)
Upvotes: 0
Reputation: 2722
Try stringi
instead if , but for gsub this should work. Also you don't need the loop, pretty sure ?gsub
is vectorized:
> example <- "file[name].tiff"
> gsub("\\[|\\]", '', example, perl = TRUE)
You can learn more about this and other horrifying realities of regex
here
Upvotes: 0