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