【问题标题】:Use tidyverse to find time-series means of cross-sectional correlations使用 tidyverse 查找横截面相关性的时间序列均值
【发布时间】:2018-05-21 18:57:24
【问题描述】:

我正在尝试找出年度横截面相关性的时间序列平均值。

tidyverse 之前,我会:

  1. dat 转换为年度数据框列表
  2. 使用lapply() 查找年度横截面相关性
  3. 使用Reduce()手动查找方法

这个逻辑有效,但不是tidy

set.seed(2001)
dat <- data.frame(year = rep(2001:2003, each = 10),
                  x = runif(3*10))
dat <- transform(dat, y = 5*x + runif(3*10))
dat_list <- split(dat[c('x', 'y')], dat$year)
dat_list2 <- lapply(dat_list, cor)
dat2 <- Reduce('+', dat_list2) / length(dat_list2)
dat2

##           x         y
## x 1.0000000 0.9772068
## y 0.9772068 1.0000000

对于tidyerse 解决方案,我最好的(也是失败的)尝试是:

  1. group_by() year 变量
  2. 每年使用do()cor()
  3. 使用map()mean() 查找元素均值

此逻辑失败并返回NULL

library(tidyverse)
dat2 <- dat %>%
  group_by(year) %>% 
  do(cormat = cor(.$x, .$y)) %>% 
  map(.$cormat, mean)
dat2

## $year
## NULL
## 
## $cormat
## NULL

上面我的非tidyverse 解决方案中是否有tidyverse 成语替换Reduce() 成语?

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:
    dat %>% 
      group_by(year) %>% 
      do(correl = cor(.data[c('x', 'y')])) %>% 
      {reduce(.$correl, `+`)/nrow(.)}
    
    
    
              x         y
    x 1.0000000 0.9772068
    y 0.9772068 1.0000000
    

    请注意,这与cor(dat[c('x', 'y')]) 完全相同,因此除非您需要单独每年的矩阵,否则无需按年份分组然后减少。这也适用于 >2 个变量。

    【讨论】:

    • 这适用于 3+ 个变量吗?我应该举一个 3+ 变量的例子。
    • 针对 >2 变量情况编辑
    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2019-12-05
    • 2020-05-24
    • 2021-11-18
    • 1970-01-01
    • 2016-03-04
    • 2020-06-23
    • 2013-11-17
    相关资源
    最近更新 更多