'How to create a single data frame with multiple vectors result of a loop operation?

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:

 n <- 0:1 
 sound1 <- readWave("D:\\sound.wav")
 result <- do.call(cbind, lapply(n, function(x) 
 meanspec(sound1,from=x,to=x+1,wl=16,plot=FALSE)))
 result1 <- data.frame(result)

The ouput will be

 structure(list(x = c(0, 2.75625, 5.5125, 8.26875, 11.025, 13.78125, 
 16.5375, 19.29375), y = c(1, 0.551383594277632, 0.0742584974502194, 
 0.0399059818168578, 0.0218500553648978, 0.0176655910374274, 
 0.00904887363707214, 
 0.00333698474894753), x.1 = c(0, 2.75625, 5.5125, 8.26875, 11.025, 
 13.78125, 16.5375, 19.29375), y.1 = c(1, 0.558106398109396, 
 0.145460335046358, 
 0.0804097312947365, 0.0476025570412434, 0.0393549921764155, 
 0.0203584314573552, 
 0.00737927765210362)), class = "data.frame", row.names = c(NA,

But in the resultant df I only need y and y.1 but no x and x.1. As you may notice x and 1.x have the same data and such iformation is redundant. In short: I only need y data.

Thankyou for your suggestions!



Solution 1:[1]

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.

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3124634
Solution 2 Ronak Shah