1 year ago
#321489
Roy
Obtaining CCF values using a loop in R
I have a data frame which looks like this:
files | Time | Male | Female |
---|---|---|---|
A | 1.1 | 0 | 1 |
A | 1.2 | 0 | 1 |
A | 1.3 | 1 | 1 |
A | 1.4 | 1 | 0 |
B | 2.4 | 0 | 1 |
B | 2.5 | 1 | 1 |
B | 2.6 | 0 | 1 |
B | 2.7 | 1 | 1 |
The 'files' column represent recording file names, 'Time' represents discretised time bins of 0.1 seconds, the 'Male' and 'Female' column represents whether the male and female are calling (1) or not (0) during that time bin.
I want to find at which lags the female and male are most correlated for all different recordings. More specifically I want the output to be a dataframe with three columns: recording file names, peak correlation score between female and male, and the lag value (at which peak correlation occurred).
I have so far could measure the peak cross-correlation of the files individually:
file1 <- dataframe %>% filter(file == unique(dataframe$`Begin File`)[1])
#obtaining observations of first file entry
Then I used following function to find peak correlation:
Find_Abs_Max_CCF <- function(a, b, e=0) {
d <- ccf(a, b, plot = FALSE, lag.max = length(a)/2)
cor = d$acf[,,1]
abscor = abs(d$acf[,,1])
lag = d$lag[,,1]
res = data.frame(cor, lag)
absres = data.frame(abscor, lag)
maxcor = max(absres$abscor)
absres_max = res[which(absres$abscor >= maxcor-maxcor*e & absres$abscor <= maxcor+maxcor*e),]
return(absres_max)
}
Find_Abs_Max_CCF(file1$f,file1$m,0.05)
Is there a way to to use a function or loop to automate the process so that I get peak correlation value, respective lag value of all the distinct file entries? Any help is highly appreciated. Thanks in advance.
Edits: I used group_map() function with following code:
part.cor<-dataframe %>% group_by(files) %>% group_map(~Find_Abs_Max_CCF(datframe$f, dataframe$m, 0.05))
However, it is returning the same values of peak correlation and lag repeated throughout output dataframe.
r
time-series
lag
data-wrangling
cross-correlation
0 Answers
Your Answer