Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rolling correlation #44

Open
wcornwell opened this issue Aug 20, 2024 · 0 comments
Open

rolling correlation #44

wcornwell opened this issue Aug 20, 2024 · 0 comments

Comments

@wcornwell
Copy link

wcornwell commented Aug 20, 2024

Hi @kevinushey,

Thanks for this package. We needed to calculate a rolling correlation between two variables, so wrote this function using your tools. If you'd like, I can make it a PR, but also happy to just leave it for people to find:

roll_cor <- function(x, y, window_size) {
  n <- length(x)
  
  # Calculate rolling sums
  sum_x <- RcppRoll::roll_sum(x,
                              n = window_size,
                              fill = NA,
                              align = "right")
  sum_y <- RcppRoll::roll_sum(y,
                              n = window_size,
                              fill = NA,
                              align = "right")
  
  # Calculate rolling sums of squares
  sum_x_sq <- RcppRoll::roll_sum(x ^ 2,
                                 n = window_size,
                                 fill = NA,
                                 align = "right")
  sum_y_sq <- RcppRoll::roll_sum(y ^ 2,
                                 n = window_size,
                                 fill = NA,
                                 align = "right")
  
  # Calculate rolling sum of products
  sum_xy <- RcppRoll::roll_sum(x * y,
                               n = window_size,
                               fill = NA,
                               align = "right")
  
  # Calculate means
  mean_x <- sum_x / window_size #could use roll_mean here
  mean_y <- sum_y / window_size #could use roll_mean here
  
  # Calculate covariance
  covariance <- (sum_xy - window_size * mean_x * mean_y) / window_size
  
  # Calculate variances
  variance_x <- (sum_x_sq - window_size * mean_x ^ 2) / window_size
  variance_y <- (sum_y_sq - window_size * mean_y ^ 2) / window_size
  
  # Calculate correlation
  correlation <- covariance / sqrt(variance_x * variance_y)
  
  return(correlation)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant