首页 > 解决方案 > mutate() 命令似乎不适用于不同类的对象

问题描述

解决了

我正在复制 Reproducible Finance with R 中使用的代码。网络研讨会的链接在这里: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.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() 函数和变量类有关,但我找不到有关此事的任何信息。非常感谢您的支持。

更新。

将一个对象的类从 更改xtsdata.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()

标签: rxtsdplyrzoo

解决方案


推荐阅读