Search code examples
rggplot2dplyrmagrittr

Is there a way to `pipe through a list'?


One really cool feature from the ggplot2 package that I never really exploited enough was adding lists of layers to a plot. The fun thing about this was that I could pass a list of layers as an argument to a function and have them added to the plot. I could then get the desired appearance of the plot without necessarily returning the plot from the function (whether or not this is a good idea is another matter, but it was possible).

library(ggplot2)
x <- ggplot(mtcars,
            aes(x = qsec,
                y = mpg)) 

layers <- list(geom_point(),
               geom_line(),
               xlab("Quarter Mile Time"),
               ylab("Fuel Efficiency"))

x + layers

Is there a way to do this with pipes? Something akin to:

#* Obviously isn't going to work
library(dplyr)
action <- list(group_by(am, gear),
               summarise(mean = mean(mpg),
                         sd = sd(mpg)))

mtcars %>% action

Solution

  • To construct a sequence of magrittr steps, start with .

    action = . %>% group_by(am, gear) %>% summarise(mean = mean(mpg), sd = sd(mpg))
    

    Then it can be used as imagined in the OP:

    mtcars %>% action
    

    Like a list, we can subset to see each step:

    action[[1]]
    # function (.) 
    # group_by(., am, gear)
    

    To review all steps, use functions(action) or just type the name:

    action
    # Functional sequence with the following components:
    # 
    #  1. group_by(., am, gear)
    #  2. summarise(., mean = mean(mpg), sd = sd(mpg))
    # 
    # Use 'functions' to extract the individual functions.