find_lag: Find the optimal lag

Description Usage Arguments Value Examples

View source: R/timeseries.R

Description

Finds the lag that maximizes the absolute correlation between two time series x and y.

Usage

1
find_lag(x, y, lag.max = as.integer(length(x)/2))

Arguments

x

time series x

y

time series y

lag.max

the maximum number of lags to investigate which defaults to the integer value of length(x)/2.

Value

an integer representign the optimal lag to apply to x

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
library(tibble)
library(ggplot2)
library(tidyr)
library(dplyr)
x <- sin(seq(1, 10, length.out = 30))
y <- lag(x, 5) + rnorm(length(x), 0, 0.2)
testdf <- tibble(id = seq_along(x), x, y)
ggplot(gather(testdf, key, val, -id), aes(y = val, x = id, color = key)) +
  geom_line()
stats::ccf(x, y, na.action = na.omit, lag.max = 5)
testdf <- mutate(testdf, z = lag(x, find_lag(x, y)))
ggplot(gather(testdf, key, val, -id), aes(y = val, x = id, color = key)) +
  geom_line()

DoktorMike/datools documentation built on Feb. 28, 2021, 8:39 a.m.