Search code examples
rloopswavacoustics

Organising large number of files into folders using R?


Apologies for the simplicity of the question as I am a novice with R.

I have a large number of 1-minute audio files, with 1 minute recorded every 5 minutes. I need them organised by hour and saved to a new folder, so every 12 files need to be saved to a new folder. I have 7472 of these files so doing this manually would take too long.

Here is an example of the file names:

20210111_000500.wav,
20210111_001000.wav,
20210111_001500.wav,
20210111_002000.wav,
20210111_002500.wav,
20210111_003000.wav,
20210111_003500.wav,
20210111_004000.wav,
20210111_004500.wav,
20210111_005000.wav,
20210111_005500.wav,

which I want to all be in one folder, with the next hour starting as 20210111_010000.wav and so on.

How would I go about doing this?

Any help is much appreciated, thank you!


Solution

  • You could try something along these lines. I first find all the .wav files, then define the folders, create the folders and finally move the .wav files to the new folders.

    library(tidyverse)
    
    setwd("path_where_wav_files_are_located_goes_here")
    
    # a vector of paths to all .wav files in the specified directory
    original_paths <- dir(pattern=".WAV$", full.names = T) %>% str_replace("\\.", getwd())
    # only the file names
    file_names <- dir(pattern=".WAV$")
    
    # creating a data.frame with original paths and new paths where files are to be moved
    df <- tibble(original_paths, file_names) %>%
      mutate(
        folder_name = (row_number() %/% 12 + 1) %>% paste0("_", .), # using integer division so that i have a dedicated folder for each 12 files
        new_path = paste0(getwd(), "/", folder_name, "/", file_names)
      )
    
    # creating the directories
    df$folder_name %>%
      unique() %>%
      paste0(getwd(), "/",  .) %>%
      map(
        ~dir.create(.x)
      )
    
    # moving the files
    walk2(df$original_paths, df$new_path, ~file.rename(.x, .y))