在R循环中命名文件 [英] Naming files in R loop

查看:608
本文介绍了在R循环中命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个音频文件,这些文件保存在工作目录的几个子文件夹中.我有一个循环,它会在每个文件的第一分钟读取内容,然后将它们另存为新文件.

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 file.

library(tuneR)

dir.create("New files")

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

for(i in 1:length(FILES)){
  OneMIN <- readWave(FILES[i], from = 0, to = 60, units = "seconds")
  writeWave(OneMIN, filename = (file=paste0(FILES[i], "_1-min.wav")))
}

现在,这有很多问题;

Now, there are a couple of things wrong with this;

1)新文件称为"File1.wav_1-min.wav",因此我需要将其重命名为"File_1-min.wav"

1) The new files are called e.g. "File1.wav_1-min.wav", so that I need to rename them to "File_1-min.wav"

2)新文件位于多个子文件夹中,然后我必须使用循环外的其他步骤将它们复制到新文件"文件夹中.

2) The new files are in multiple subfolders, and I have to then copy them to the "New files" folder using additional steps outside the loop.

我有解决这些问题的解决方法,但是我敢肯定,通过在循环中添加其他行,可以找到一种更优雅的方法.我想:

I have workarounds to resolve these issues, but I'm sure there is a more elegant way to do this, by including additional lines in the loop. I would like to:

1)删除文件名中的第一个".wav"

1) Strip out the first '.wav' in the file name

2)自动将它们保存到新文件"文件夹中

2) Automatically save them to the "New files" folder

但是,我对如何解决这个问题一无所知.任何建议表示赞赏.谢谢.

However, I don't have an idea about how to go about this. Any suggestions are appreciated. Thanks.

推荐答案

file.path()函数可用于将目录和文件名组合为单个文件路径,而sub()函数可让您轻松修改文件名:

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)
}

此外,值得注意的是,在原始代码示例中,list.files()函数将仅返回每个文件路径的文件名部分.

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)

和:

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

这将确保infileoutfile都指向正确的位置.

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

这篇关于在R循环中命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆