mutate() 命令似乎不适用于不同类别的对象

问题描述

解决

我正在使用 R 复制在 Reproducible Finance 中使用的代码。网络研讨会的链接在这里https://www.rstudio.com/resources/webinars/reproducible-finance-with-r/

练习的数据是从雅虎财经下载的。 .csv 文件在这里http://www.reproduciblefinance.com/data/data-download/

按照网络研讨会上提供的说明,我发现代码无法像课程中那样工作:

portfolio_returns_tidyquant_rebalanced_monthly %>%  
        mutate(
                dplyr_port_returns = portfolio_returns_dplyr_byhand$returns,xts_port_returns = coredata(portfolio_returns_xts_rebalanced_monthly)
                )%>%
        head()

系统不提供任何输出,也不显示代码中是否有错误

然后我决定消除我想创建的每个新变量,看看是否会发生什么。事实证明,如果 mutate() 命令中不包含一个变量,系统会生成我需要的部分输出。下面是代码输出

portfolio_returns_tidyquant_rebalanced_monthly %>%  
        mutate(
                dplyr_port_returns = portfolio_returns_dplyr_byhand$returns,#  xts_port_returns = coredata(portfolio_returns_xts_rebalanced_monthly)
                )%>%
        head(2)
日期 返回 dplyr_port_returns
2013-01-31 0.0308487341 0.0308487341
2013-02-28 -0.0008697461 -0.0008697461

另外,关于变量的一些信息:

class(portfolio_returns_xts_rebalanced_monthly)
[1] "xts" "zoo"

class(portfolio_returns_dplyr_byhand)
[1] "tbl_df"     "tbl"        "data.frame"

portfolio_returns_xts_rebalanced_monthly 是使用以下代码创建的:

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

prices <-
        getSymbols(
                symbols,src = 'yahoo',from = "2012-12-31",to = "2017-12-31",auto.assign = T,warnings = F
        ) %>%
        map(~Ad(get(.))) %>% 
        reduce(merge) %>% 
        `colnames<-`(symbols)
w <- c(
        0.25,0.25,0.20,0.10
)

prices_monthly <-
        to.monthly(
                prices,indexAt = "lastof",OHLC = FALSE
        )

assets_return_xts <- na.omit(
        Return.calculate(
                prices_monthly,method = "log"
        )
)

portfolio_returns_xts_rebalanced_monthly <- 
        Return.portfolio(
                assets_return_xts,weights = w,rebalance_on = 'months'
        ) %>% 
        `colnames<-`("returns")

我很确定这与 mutate() 函数和变量类有某种联系,但我找不到有关此事的任何信息。非常感谢您的支持

更新。

一个对象的类从 xts 更改为 data.frame,并稍微调整一下代码解决了问题。

更新的代码

portfolio_returns_xts_rebalanced_monthly_df <-
  data.frame(
    date=index(portfolio_returns_xts_rebalanced_monthly),coredata(portfolio_returns_xts_rebalanced_monthly)
    )

portfolio_returns_tidyquant_rebalanced_monthly %>%  
        mutate(
                dplyr_port_returns = portfolio_returns_dplyr_byhand$returns,xts_port_returns = portfolio_returns_xts_rebalanced_monthly_df$returns
                )%>%
        head()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)