Search code examples
rtidyverse

Renaming files with r library("tidyverse”)


I'm trying to rename a bunch of files in r with library("tidyverse”).

As is: Snap-551-Image Export-01_c1_ORG.tif

The bold section is a running number, starting at 01 going to 150, each number combined with _c1 and _c2

TO be: 001_551_c1_AE2315_01.tif

The first 20 files are from the same sample. Therefore, the naming for those should have the same sample number, here 001 in bold. The original number should be used at the end of the new file name.

enter image description here

I would very much appreciate any help on this :-) Thanks a lot & best, Andi


Solution

  • This uses regular expressions (regex) to create a vector of new names based on the original names of your .tif files, then uses that vector to rename your files. As others have stated, this can be achieved using base R, but if you want a tidyverse solution, here is how to do it using the dplyr and stringr packages.

    If you exclude the select() function, you will be able to see the individual steps used to create the file names e.g. the id_num columns. The three regex could be done in one, but my skills don't extend that far. Plus, using three different steps arguably makes it easier to follow if you are not familiar with regex.

    It will still work even if you have multiple series numbers e.g. 551, 552 etc.

    library(dplyr)
    library(stringr)
    
    # Set working directory to where tif files are stored (change to suit)
    setwd("C:/folder/where/tif/files/stored")
    
    # Create dataframe with vector of tif file names
    file_list <- data.frame(old_name = list.files(pattern = "^Snap.*\\.tif$"))
    
    # Create column with vector of new names (based on your example)
    file_list <- file_list |>
      mutate(
        id_num1 = str_extract(old_name, "(?<=Snap-)[0-9]+"),
        id_num2 = str_extract(old_name, "(?<=Image Export-)[0-9]+"),
        id_num3 = str_extract(old_name, "(?<=_c)[0-9]+"),
        new_name = sprintf("%03d_%s_c%s_AE2315_%02d.tif",
                           as.integer(id_num2),
                           id_num1,
                           id_num3,
                           as.integer(id_num2))) |>
      select(old_name, new_name)
    
    # Rename file_list
    file.rename(file_list$old_name, file_list$new_name)