Search code examples
rtidyr-corrplot

R Tidy correlogram by group


I would like to use a tidy approach to produce correlograms by group. My attempt with iris and libraries dplyr and corrplot:

library(corrplot)
library(dplyr)

par(mfrow=c(2,2))
iris %>%
  group_by(Species) %>%
  group_map(~ corrplot::corrplot(cor(.x,use = "complete.obs"),tl.cex=0.7,title =""))

It works but I would like to add the Species name on each plot. Also, any other tidy approaches/ functions are very welcome!


Solution

  • We could use cur_group()

    library(dplyr)
    library(corrplot)
    out <- iris %>% 
          group_by(Species) %>%
           summarise(outr = list( corrplot::corrplot(cor(cur_data(),
                use = "complete.obs"),tl.cex=0.7,title = cur_group()[[1]])))
    
    

    Or if we are using group_map, the .keep = FALSE by default. Specify it as TRUE and extract the group element

    iris %>%
      group_by(Species) %>%
      group_map(~ corrplot::corrplot(cor(select(.x, where(is.numeric)),
          use = "complete.obs"),tl.cex=0.7,title = first(.x$Species)), .keep = TRUE)