有没有办法`管道列表'?

Ben*_*min 8 r ggplot2 dplyr magrittr

ggplot2我从未真正开发的包中的一个非常酷的功能是在图中添加图层列表.有趣的是,我可以将一个图层列表作为参数传递给函数,并将它们添加到图中.然后,我可以获得所需的情节外观,而不必从功能中返回情节(这是否是一个好主意是另一回事,但它是可能的).

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
Run Code Online (Sandbox Code Playgroud)

有没有办法用管道做到这一点?类似于:

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

mtcars %>% action
Run Code Online (Sandbox Code Playgroud)

Fra*_*ank 16

要构建一系列magrittr步骤,请从 .

action = . %>% group_by(am, gear) %>% summarise(mean = mean(mpg), sd = sd(mpg))
Run Code Online (Sandbox Code Playgroud)

那么它可以像OP中想象的那样使用:

mtcars %>% action
Run Code Online (Sandbox Code Playgroud)

像a一样list,我们可以通过子集来查看每个步骤:

action[[1]]
# function (.) 
# group_by(., am, gear)
Run Code Online (Sandbox Code Playgroud)

要查看所有步骤,请使用functions(action)或只输入名称:

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. 
Run Code Online (Sandbox Code Playgroud)