首页 文章

多滚动相关

提问于
浏览
0

我试图解决的问题是计算数据框中选定列的滚动相关性 . 我想使用列名来驱动滚动功能:

我的功能

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)

关于如何使这项工作或任何其他想法的任何想法?

提前致谢 .

1 回答

  • 0
    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)
    

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

相关问题