Множественная скользящая корреляция
Проблема, которую я пытаюсь решить, состоит в том, чтобы вычислить скользящую корреляцию по выбранным столбцам во фрейме данных. Я хочу использовать имена столбцов для управления функциями прокрутки:
моя функция
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 ответ
Решение
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- прокомментировано 4 мая 2017 г. https://github.com/r-lib/rlang/issues/116