0

我希望将“multiple_sounds”函数应用于使用 R 的文件夹中的 .WAV 文件列表。这是我当前的代码:

##### 1 #####
setwd("E:/Audiomoth Files/Winter/Rural/Emma/_1")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "ndsi_results.csv", soundindex = "ndsi", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "adi_results.csv", soundindex = "acoustic_diversity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "aei_results.csv", soundindex = "acoustic_evenness", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "aci_results.csv", soundindex = "acoustic_complexity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_1", resultfile = "H_results.csv", soundindex = "bioacoustic_index", no_cores = "-2")

##### 2 #####
setwd("E:/Audiomoth Files/Winter/Rural/Emma/_2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "ndsi_results.csv", soundindex = "ndsi", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "adi_results.csv", soundindex = "acoustic_diversity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "aei_results.csv", soundindex = "acoustic_evenness", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "aci_results.csv", soundindex = "acoustic_complexity", no_cores = "-2")
multiple_sounds(directory = "E:/Audiomoth Files/Winter/Rural/Emma/_2", resultfile = "H_results.csv", soundindex = "bioacoustic_index", no_cores = "-2")

这可行,但目前我必须每次为每个文件夹(_1、_2、_3 等)复制并粘贴此代码,其中有 623 个,因此手动执行此操作非常耗时。

有没有一种方法可以自动更改文件路径以自动将目录更改为 _3、_4、_5 并将函数循环应用到第 623 个文件夹?

先感谢您

4

1 回答 1

2

我建议编写一个实用函数并将目录用作输入:

apply_wav_index = function(
  dir,
  index = c("ndsi", "acoustic_diversity", "acoustic_evenness", "acoustic_complexity", "bioacoustic_index"),
  labels = c("ndsi", "adi", "aei", "aci", "H"),
  ...
) {
  if(length(index) != length(labels)) stop("Must provide same number of labels and indexes")
  for(i in seq_along(index)) {
    multiple_sounds(
      directory = dir,
      resultfile = paste0(dir, "/", labels[i], "_results.csv"),
      soundindex = index[i],
      ...
    )
  }
}

然后你应该可以这样称呼它:

for(i in 1:6) {
  apply_wav_index(dir = paste0("E:/Audiomoth Files/Winter/Rural/Emma/_", i), no_cores = "-2")
}

您还可以使用list.dirs().

于 2021-04-22T16:27:03.853 回答