As of
packageVersion("dplyr")
[1] ‘1.0.2’
The result of the code suggested in one of the answers returns a tibble
iris %>%
group_by(Species) %>%
do(cormat = cor(select(., -matches("Species"))))
# A tibble: 3 x 2
# Rowwise:
Species cormat
<fct> <list>
1 setosa <dbl[,4] [4 × 4]>
2 versicolor <dbl[,4] [4 × 4]>
3 virginica <dbl[,4] [4 × 4]>
To get the data into a rectangular shape, you can
iris_cor <- iris %>%
group_by(Species) %>%
do(cormat = cor(select(., -matches("Species")))) %>%
pull(cormat) %>% melt
You will have the levels of Species codified on L1 variable.
Var1 Var2 value L1
1 Sepal.Length Sepal.Length 1.0000000 1
2 Sepal.Width Sepal.Length 0.7425467 1
3 Petal.Length Sepal.Length 0.2671758 1
4 Petal.Width Sepal.Length 0.2780984 1
...
I am sure there's a cleaner way of doing this with unnest() and its friends, but couldn't figure out yet. Hoping this gets noticed
and posts a better solution