How to apply corrr::correlate by group?


#1

For example, I'd like to get correlation matrix by 'Species' from 'iris' dataset.

library(pacman)
p_load(tidyverse,corrr)

below code works.
correlate(iris[-5])

but what I want to do is like below code, which doesn't work:

group_by(iris, Species) %>%
    correlate()

I found a solution, but ANY more short, elegant code using tidyverse?

group_by(iris,Species) %>%
    nest() %>%
    mutate(cordf = map(data, correlate)) %>%
    unnest(cordf)

If python::pandas , below is available

iris.groupby('Species').corr()

If using reticulate, above is same as below

library(reticulate)
pd = import('pandas')
df = pd$DataFrame(iris %>% dict)
df$groupby('Species')$corr()

#2

Could you please turn this into a self-contained reprex (short for minimal reproducible example)? It will help us help you if we can be sure we're all working with/looking at the same stuff.

If you've never heard of a reprex before, you might want to start by reading the tidyverse.org help page. The reprex dos and don'ts are also useful.

For pointers specific to the community site, check out the reprex FAQ, linked to below.