Custom ccf function using tidymodels or correlation R package

35 views Asked by At

I'm using the ccf function in R to do cross-correlation between two time series, but my boss wants (1) the output to consider only positive values of lag and (2) to not use pearson but spearman method. For the former requirement, I have found no much help nor for the second one see 1 and 2.

My question are:

  1. Are you aware of any package which offer already these options?
  2. Otherwise, I have been studying corrr from tidymodels or correlation from easystats which are improved and more modern functions to compute correlations. I could use one of those functions in a loop, compute the correlation with my desired method, shift the values of one of the input time series each turn of the loop, compute the correlation and so on. Would this be correct or am I missing something?

I tried to read ccf documentation and I found no clue on how to achieve this, so that's why I'm looking for an alternative or what I should consider in order to code it myself.

1

There are 1 answers

3
Carl On

Possible option:

library(ggplot2)
library(funtimes)

x <- rnorm(100)
y <- rnorm(100)

# All lags and positive lags only
ccf_boot(x, y, plot = "Spearman") |> 
  ggplot(aes(Lag, r_S)) +
  geom_ribbon(aes(ymin = lower_S, ymax = upper_S), fill = "skyblue") +
  geom_point() +
  geom_col(width = 0.05) +
  coord_cartesian(xlim = c(0, NA)) +
  labs(
    y = "CCF", title = "Spearman correlation",
    subtitle = "with 95% bootstrap confidence region")

Created on 2024-03-11 with reprex v2.1.0