多重滚动相关

Multiple rolling correlation

我要解决的问题是计算数据框中选定列的滚动相关性。我想使用列名来驱动滚动函数:

我的函数

library(tidyquant)

rolling_cor <- function(df, col1, col2, window.length){

  col1 <- as.name(col1)
  col2 <- as.name(col2)

    xx <- df %>%
    tq_mutate_xy(x          = col1, 
                 y          = col2,
                 mutate_fun = runCor,
                 n          = window.length,
                 col_rename = glue(str_sub(col1,1,3), "_",str_sub(col2,1,3), "_", str_sub(col1,4,6)))
  return(xx)

}

功能测试

aapl <- tq_get("aapl")

aapl_roll_cor <- rolling_cor(aapl, col1 = "open" , col2 = "high", 15)

关于如何实现这项工作的任何想法或任何替代想法?

提前致谢。

rolling_correlation <- function(df, vector.1, vector.2, window.length = 15){


  require(rlang)
  require(tidyquant)
  require(tibbletime)

  #build the correlation formula
  cor_roll <- rollify(~cor(.x, .y), window = window.length)


  x <- map2(vector.1, vector.2, ~mutate(df, 
                                        running_cor = cor_roll(!!quo(!! sym(.x)), 
                                                               !!quo(!! sym(.y))))) %>%
    stats::setNames(., paste(vector.1, vector.2, sep = "_")) %>%                            # name the dfs in the list
    bind_rows(.id = "groups") %>% spread(groups, running_cor)                               # add the list name as a column in the DF and then spread it

  return(x)

}
例子
data("FB")
corr_df <- rolling_correlation(FB, c("open", "high", "low"), c("close", "low", "open"), 5)

取消引用的帮助!!quo(!! sym(.x)) 来自这里 - 看看 lionel - 2017 年 5 月 4 日评论 https://github.com/r-lib/rlang/issues/116