r语言 - Tibbletime,tq_transmute产生奇怪的错误,列显然存在,但说它不存在



我本可以在一周前保证这段代码有效,但我想我错了。我一直收到错误:错误:无法对不存在的列进行子集设置。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)

相关内容

  • 没有找到相关文章

最新更新