JMDR JMDR - 1 month ago 15
R Question

Name output from a for loop using a list in R

I have a list of audio recordings that I am using a for loop to read in, clip, rename, and write out. I am trying to rename the clips using random numbers from an associated "master" table so that the clips can be used in a randomized blind study.

The code below works as desired with

sample(100:999,1)
in place of the code between the triple tildes (
~~~
) below (which doesn't run, but hopefully shows the desired outcome), but there is the small chance of getting duplicate clipIDs. How do I get the output of each loop iteration to be named by it's corresponding ID?

recording_list <- recording_summary$Original_filename # chr [1:100]
clipID_list <- recording_summary$ClipID # int [1:100]

for (i in c(recording_list)){
wavIN <- readWave(i, from=120, to=301, units="seconds")
writeWave(wavIN, paste0(~~~i in c(clipID_list)~~~, ".wav"))
rm(wavIN)
}

Answer

When I am moving along multiple variables, I tend to use an index (or name) instead. This should work for you:

recording_list <- recording_summary$Original_filename # chr [1:100]
clipID_list <- recording_summary$ClipID # int [1:100]

for (idx in 1:length(recording_list)){
  wavIN <- readWave(recording_list[idx], from=120, to=301, units="seconds")
  writeWave(wavIN, paste0(clipID_list[idx], ".wav"))
  rm(wavIN)
}
Comments