dplyr中分组变量的相关矩阵

Correlation matrix of grouped variables in dplyr

我有一个包含 50 个数字列的分组数据框(使用 dplyr),这些列使用其中一列分成组。我想计算所有非分组列和一个特定列之间的相关矩阵。

mtcars 数据集的示例:

data(mtcars)
cor(mtcars[,2:11], mtcars[,2])

returns 每帆船英里数与其他变量之间的相关性列表。

但是,假设我希望为每组气缸计算相同的相关性,例如:

library(dplyr)
mtcars <-
    mtcars %>%
    group_by(cyl)

我该怎么做?我在想

mtcars %>%
    group_by(cyl) %>%
    summarise_each(funs(cor(...))

但我不知道在 ... 中放什么,因为我不知道如何在 dplyr 链中指定列。

相关: Linear model and dplyr - a better solution? has an answer which is very similar to @akrun's answer. Also, over on cross validated: https://stats.stackexchange.com/questions/4040/r-compute-correlation-by-group 有其他使用非 dplyr.

软件包的解决方案

我们可以使用 do.

library(dplyr)
mtcars %>% 
       group_by(cyl) %>%
       do(data.frame(Cor=t(cor(.[,3:11], .[,3]))))
# A tibble: 3 x 10
# Groups:   cyl [3]
#    cyl Cor.disp Cor.hp Cor.drat Cor.wt Cor.qsec Cor.vs Cor.am Cor.gear Cor.carb
#  <dbl>    <dbl>  <dbl>    <dbl>  <dbl>    <dbl>  <dbl>  <dbl>    <dbl>    <dbl>
#1     4     1.00  0.435  -0.500   0.857    0.328 -0.187 -0.734  -0.0679   0.490 
#2     6     1.00 -0.514  -0.831   0.473    0.789  0.637 -0.637  -0.899   -0.942 
#3     8     1     0.118  -0.0922  0.755    0.195 NA     -0.169  -0.169    0.0615

注意: t部分由@Alex

贡献

或使用group_modify

mtcars %>%
    select(-mpg) %>% 
    group_by(cyl) %>%
    group_modify(.f = ~ as.data.frame(t(cor(select(.x, everything()), 
          .x[['disp']]))))
# A tibble: 3 x 10
# Groups:   cyl [3]
#    cyl  disp     hp    drat    wt  qsec     vs     am    gear    carb
#  <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl>  <dbl>  <dbl>   <dbl>   <dbl>
#1     4  1.00  0.435 -0.500  0.857 0.328 -0.187 -0.734 -0.0679  0.490 
#2     6  1.00 -0.514 -0.831  0.473 0.789  0.637 -0.637 -0.899  -0.942 
#3     8  1     0.118 -0.0922 0.755 0.195 NA     -0.169 -0.169   0.0615

或者另一种选择是 summariseacross。创建了一个新列 'disp1' 作为 'disp' 然后按 'cyl' 分组,得到列 'disp' 到 'carb' 的 cor 和 'disp1'

 mtcars %>%
     mutate(disp1 = disp) %>%
     group_by(cyl) %>% 
     summarise(across(disp:carb, ~ cor(., disp1)))
# A tibble: 3 x 10
#    cyl  disp     hp    drat    wt  qsec     vs     am    gear    carb
#* <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl>  <dbl>  <dbl>   <dbl>   <dbl>
#1     4  1.00  0.435 -0.500  0.857 0.328 -0.187 -0.734 -0.0679  0.490 
#2     6  1.00 -0.514 -0.831  0.473 0.789  0.637 -0.637 -0.899  -0.942 
#3     8  1     0.118 -0.0922 0.755 0.195 NA     -0.169 -0.169   0.0615

library(data.table)
d1 <- copy(mtcars)
setnames(setDT(d1)[, as.list(cor(.SD, .SD[[1]])) , cyl, 
                            .SDcols=3:11],  names(d1)[2:11])[]