我有一个dataframes列表,其中包括一个日期列,一个月度股票回报列和一系列不同的列(每月)风险参数(确切地说是180).我把我的数据按月和年分组,目的是迭代列表中的每个dataframe,计算返回列和每个风险参数之间的协方差,返回年协方差即每年180个协方差。
数据如下所示:(https://i.stack.imgur.com/19jeH.png)
我已经弄清楚了如何使用以下代码在单个 Dataframe 中对单个风险参数执行此操作:
df <- df %>%
mutate(month = format(date, "%m"), year = format(date, "%Y")) %>% group_by(year) %>%
summarise(cov = cov(ret, Natural.disasters))
这将给出以下输出:(https://i.stack.imgur.com/VjzIo.png)
我只是不知道如何在回报和其他风险参数之间做到这一点。有什么建议吗?
尝试了不同的循环,但似乎都不起作用。还尝试了lapply()函数,但我无法使其工作。
1条答案
按热度按时间jecbmhm31#
我自己想出来的。代码如下:
基本上,该函数循环遍历一个 Dataframe 列表,并计算我的返回列和每个风险参数之间的协方差。