Naming files in R loop

后端 未结 2 375
生来不讨喜
生来不讨喜 2021-01-23 13:53

I have multiple audio files which are held in several subfolders in my working directory. I have a loop which reads in the first minute of each file and then saves them as a new

2条回答
  •  攒了一身酷
    2021-01-23 14:20

    The file.path() function can be used to combined directories and filenames into a single filepath, while the sub() function will allow you to easily modify the filenames:

    library(tuneR)
    
    dir.create("New files")
    
    FILES <- list.files(PATH, pattern = "audio", recursive = TRUE)
    
    for(infile in FILES){
      OneMIN <- readWave(infile, from = 0, to = 60, units = "seconds")
      outfile <- file.path("New files", sub('.wav', '_1-min.wav', infile))
      writeWave(OneMIN, filename=outfile)
    }
    

    Also, it's worth noting that in the original code sample, the list.files() function will only return the filename part of each filepath.

    Thus, you may need to modify your code to look something like:

    FILES <- list.files(PATH, pattern = "audio", recursive = TRUE, full.names=TRUE)
    

    and:

    outfile <- file.path("New files", sub('.wav', '_1-min.wav', basename(infile)))
    

    This will ensure that both infile and outfile are pointing to the correct locations.

提交回复
热议问题