在r中查找 Dataframe 中1列与其他列的范围之间的协方差

dced5bon  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(115)

我有一个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()函数,但我无法使其工作。

jecbmhm3

jecbmhm31#

我自己想出来的。代码如下:

#Split df into list of df's by permno
df.list <- split(Merged_df , f = Merged_df$permno )

# Function that loops through list of dfs and calculates yearly 
# covariance between return and narratives
cov_df_wide_list[1:2] <- lapply(df.list, function(df) {
  # create a new column with year information
  df <- df %>%
    mutate(year = lubridate::year(date))

  # group the dataframe by year and each parameter column
  # and calculate the covariance with the return column
  cov_df <- df %>%
    select(year, permno, Natural.disasters:Revenue.growth, ret) %>%
    gather(key = "param_col", value = "value", -year, -permno, -ret) %>%
    group_by(year, permno, param_col) %>%
    summarize(cov = cov(value, ret))

  # spread the dataframe to get each year's covariances
  cov_df_wide <- cov_df %>%
    spread(key = "param_col", value = "cov")

  return(cov_df_wide)
})

基本上,该函数循环遍历一个 Dataframe 列表,并计算我的返回列和每个风险参数之间的协方差。

相关问题