If my above guess is correct, I would suggest using the following approach:
my_data %>%
group_nest(group) %>%
mutate(cors = map(data, corrr::correlate),
stretch = map(cors, corrr::stretch)) %>%
unnest(stretch)
Here is a breakdown of what this code is doing:
- First off, the
%>% is just a way of output of one function as the input to the next function (or, in the case of the first step, simply passing the data forward)
- Next,
group_nest() will group the data by your group variable, and nest them as data frames inside your data frame. This is a more advanced concept, but a very powerful one. Try just running my_data %>% group_nest(group) to see exactly what is happening here. The 25 observations that belong to each group are now stored in their own separate tibbles (a type of data frame), which makes it easier to apply functions to each data set
-
mutate() creates new variables, so we add the column cors which is the pairwise correlations for every pair of variables, and it loops over the data for each of the 4 groups. Then we create the variable stretch, which turns the correlation table from wide to long.
- Lastly, we can use
unnest(), which does the opposite of nesting functions. It will take the column of data frames and unpack them back into our main data frame
# A tibble: 64 x 6
group data cors x y r
<chr> <list> <list> <chr> <chr> <dbl>
1 cat1 <tibble [25 x 4]> <tibble [4 x 5]> a a NA
2 cat1 <tibble [25 x 4]> <tibble [4 x 5]> a b 0.170
3 cat1 <tibble [25 x 4]> <tibble [4 x 5]> a c 0.411
4 cat1 <tibble [25 x 4]> <tibble [4 x 5]> a d 0.204
5 cat1 <tibble [25 x 4]> <tibble [4 x 5]> b a 0.170
6 cat1 <tibble [25 x 4]> <tibble [4 x 5]> b b NA
7 cat1 <tibble [25 x 4]> <tibble [4 x 5]> b c 0.0285
8 cat1 <tibble [25 x 4]> <tibble [4 x 5]> b d 0.133
9 cat1 <tibble [25 x 4]> <tibble [4 x 5]> c a 0.411
10 cat1 <tibble [25 x 4]> <tibble [4 x 5]> c b 0.0285
# ... with 54 more rows
The results shown above present the pairwise (x-y) correlations (r) for every group. We can also relatively easily spin this into a plot, one for each group.
library(ggplot2)
my_data %>%
group_nest(group) %>%
mutate(cors = map(data, corrr::correlate),
stretch = map(cors, corrr::stretch)) %>%
unnest(stretch) %>%
ggplot(aes(x, y, fill = r)) +
geom_tile() +
facet_wrap(~group)