
Find the lag at which cross-correlation between two time series is maximised
Source:R/analysis_functions.R
cross_corr.RdComputes the cross-correlation function (CCF) between x_var and
y_var for lags from -max_lag to 0 using
ccf, then returns the lag with the highest CCF for each
group. Only non-positive lags are considered (i.e. x_var leading
y_var), reflecting the assumption that changes in the primary series
precede changes in the secondary series.
Arguments
- dat
A data frame containing the two time series and a grouping column.
- date_var
Character string giving the name of the date column. Required when
subset_dateis non-NULL. When supplied, rows are sorted bydate_varwithin each group before the CCF is computed (required becauseccfassumes row order is chronological). IfNULL,datmust already be sorted chronologically within each group.- grp_var
Character string giving the name of the grouping column. The CCF is computed separately within each group.
- x_var
Character string giving the name of the primary (leading) time series column.
- y_var
Character string giving the name of the secondary (lagged) time series column.
- max_lag
Integer. Maximum number of lags to evaluate. CCF is computed for lags
-max_lagto 0. Default is 20.- subset_date
Character string in the same format as
date_var. If supplied, only rows with dates on or beforesubset_dateare used. Requiresdate_varto be specified.
Value
A tibble with one row per group containing:
<grp_var>Group identifier; column name matches
grp_var.lagInteger \(\leq 0\). The lag at which the CCF between
x_varandy_varis highest within that group.
See also
rolling_corr to compute rolling correlation at the
identified lag; ccf for the underlying CCF method.