Home > database >  How to create a single data frame with multiple vectors result of a loop operation?
How to create a single data frame with multiple vectors result of a loop operation?

Time:02-19

I have a .wav file and want to get power spectrums for successive no overlapping time windows. The data of the power spectrum is obtained with the next function, once seewave and tuneR libraries are loaded:

  Sound1 <- readWave("D:\\Sound.wav")
  meanspec(sound1,from=0,to=1,plot=FALSE)

Then, two vectors showing frequency and amplitude (from 0s to 1s) are obtained. The next step is to storage in a single df the intensity data obtained from multiple consecutive time widows of a defined duration t (with t = 1s it will be 0-1, 1-2, 2-3, 3-4, 4-5 s and so forth). The data frame will contain several vectors, each of them with the intensities for each time widow but without the frequency values as they do not change over time.

Thankyou for your suggestions!

CodePudding user response:

There are more than a few ways to do what you are talking about. I don't know the length of the vector you are talking about though or the way meanspec returns its data, so you will have to fill that in yourself

vec_length <- length(amplitude_vector)
wav_df <- data.frame(matrix(nrow = 0, ncol = vec_length   1))

for(i in 0:(end-1)){
    #Add relevant code to get the amplitude vector from the function below
    amp_vec <- meanspec(sound1, from = i, to = i 1, plot = FALSE)... 
    wav_df <- rbind(wav_df,c(i,amp_vec))
}

colnames(wav_df) <- c("start-time",...)#Add in the other column names that you want

wav_df should then have the information you want.

CodePudding user response:

You may use lapply -

n <- 0:9 #to end at 9-10;change as per your preference
Sound1 <- readWave("D:\\Sound.wav")
result <- do.call(rbind, lapply(n, function(x) 
                  meanspec(sound1,from=x,to=x 1,plot=FALSE)))
result
#to get dataframe as output
#result <- data.frame(result)
  • Related