Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R – pull title for corrplot graph within map in a pipeline

Imagine this piece of code:

mtcars %>% 
    group_split(cyl) %>% 
    map(select, mpg, disp, hp) %>% 
    `names<-`(c(4, 6, 8)) %>% 
    map(cor)

The names of the list elements are set according to the value of the cyl variable, based on which the data was split into three groups.

Now imagine passing all of this to corrplot:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mtcars %>% 
    group_split(cyl) %>% 
    map(select, mpg, disp, hp, cyl) %>% 
    `names<-`(c(4, 6, 8)) %>% 
    map(cor) %>% 
    map(corrplot)

Works nicely. Now, the corrplot function has a title argument, which is used to print titles on the plot. I want the title of each plot to be pulled from the name of the list element which was used to create the plot – in other words, those values of the cyl variable that were mentioned previously. How can I do this? I tried doing this:

mtcars %>% 
    group_split(cyl) %>% 
    map(select, mpg, disp, hp) %>% 
    `names<-`(c(4, 6, 8)) %>% 
    map(cor) %>% 
    map(corrplot, title = names(.))

But this just prints ALL the names on the graph and not just the ones from the current element.

If you have a solution, I would be very thankful. Without breaking the pipeline, because I can find the workaround with breaking the pipeline quite easily.

>Solution :

We can use imap/iwalk instead of map

library(dplyr)
library(purrr)
library(corrplot)
mtcars %>% 
    group_split(cyl) %>% 
    map(select, mpg, disp, hp) %>% 
    `names<-`(c(4, 6, 8)) %>% 
    map(cor) %>% 
   imap(~ corrplot(.x, title = .y))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading