r - 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() 函数和变量类有关,但我找不到有关此事的任何信息。非常感谢您的支持。
更新。
将一个对象的类从 更改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()
解决方案
推荐阅读
- mysql - 从数据库(php、mysql、laravel)编码 blob 后图像不加载
- php - 将布尔值从 Ajax 传递到 PHP
- python - 如何提取可变的json键的值
- tensorflow - 从张量流估计器将多个损失分量输出到张量板
- java - Apache Nifi - 无法启动 Ni-Fi 实例
- asp.net - 适用于 Visual Basic 的 ExcelDataReader
- javascript - JSON中ajax调用返回值的Javascript访问元素
- node.js - Next.js 拦截响应
- bash - 检查 Number 是否乘以(给定数字)并分配给变量
- angular - X509 证书未正确显示到期日期。时间戳有特殊格式吗?