Skip to contents

This function calculates the optimal lag between two time series by finding the lag that maximizes their cross-correlation. It's particularly useful for synchronizing recordings from different sources, such as physiological and behavioral data.

Usage

find_lag(signal, reference, max_lag = 5000, normalize = TRUE)

Arguments

signal

Time series to align (numeric vector)

reference

Reference time series to align against (numeric vector)

max_lag

Maximum lag to consider in both directions, in number of samples. If NULL, uses (length of series - 1)

normalize

Logical; if TRUE, z-score normalizes both series before computing cross-correlation (recommended for series with different scales)

Value

Integer indicating the optimal lag. A positive value means the signal needs to be shifted forward in time to align with the reference. A negative value means the signal needs to be shifted backward.

See also

align_timeseries for applying the computed lag

Examples

# Create two artificially shifted sine waves
t <- seq(0, 10, 0.1)
reference <- sin(t)
signal <- sin(t - 0.5)  # Signal delayed by 0.5 units
lag <- find_lag(signal, reference)
print(lag)  # Should be approximately 5 samples (0.5 units)
#> [1] -5