tq_transmute 的 tibbletime 产生奇怪的错误,列显然存在但说它不存在

tibbletime with tq_transmute producing strange error, column obviously exists but says it doesn't

我本可以在一周前发誓这段代码有效,但我想我错了。我不断收到错误消息:错误:无法对不存在的列进行子集化。 x 列 asset 不存在。 运行 rlang::last_error() 看看哪里出错了。 另外: 警告信息: ... 对于未分组的数据帧不能为空。 你想要 data = everything() 吗?

我已经一步一步地尝试查看它在我的代码中的位置,我可以说它是在我对资产进行分组之后,并且在我开始添加 tq_transmute 时发生的.如果有人可以提供帮助,将不胜感激。我将提供您应该能够自动 运行 的代码,看看我在说什么。这没有任何意义,因为“资产”在收集数据并分组后确实存在。

library(tidyverse)
library(lubridate) 
library(readxl)
library(highcharter) 
library(tidyquant) 
library(timetk) 
library(tibbletime) 
library(quantmod) 
library(PerformanceAnalytics)
library(scales)
library(magrittr)
library(broom)
library(purrr)

symbols <- c("SPY", "EFA", "IJS", "EEM", "AGG")

prices <- getSymbols(symbols,
                     src = 'yahoo',
                     from = "2012-12-31",
                     to = "2017-12-31",
                     auto.assign = TRUE,
                     warnings = FALSE) %>%
  map(~Ad(get(.)))%>% #the period here in get(.) refers to our intial object
  reduce(merge) %>%
  `colnames<-`(symbols)


# WHERE MY PROBLEM OCCURS 
asset_returns_tbltime <-
  prices %>% 
  tk_tbl(preserve_index = TRUE,
                    rename_index = "date")%>%
  # this is the the tibbletime function
  as_tbl_time(index = date) %>% 
  as_period(period = "month",
            side = "end") %>%
  gather(asset, returns, -date) %>%
  group_by(asset) %>% 
  tq_transmute(mutate_fun = periodReturn, #GETTING THE ERROR SOMEWHERE IN HERE
                                   type = "log") %>%
  spread(asset, monthly.returns) %>%
  select(date, symbols) %>%
  slice(-1)

gather 已替换为 pivot_longerspread 已替换为 pivot_wider。如果您将 gather 代码更改为 pivot_longer,它就可以工作。我不太确定为什么它会因 gather 而失败。

prices %>% 
  tk_tbl(preserve_index = TRUE,
         rename_index = "date")%>%
  as_tbl_time(index = date) %>% 
  as_period(period = "month",
            side = "end") %>%
  pivot_longer(cols = -date, names_to = 'asset', values_to = 'returns') %>%
  group_by(asset) %>%
  tq_transmute(mutate_fun = periodReturn, type = "log")  %>%
  pivot_wider(names_from = asset, values_from = monthly.returns) %>%
  select(date, symbols) %>%
  slice(-1)