有没有一种方法可以“遍历列表”? [英] Is there a way to `pipe through a list'?
问题描述
我从未真正充分利用过的 ggplot2
包中的一个非常酷的功能是在绘图中添加图层列表。有趣的是,我可以将图层列表作为参数传递给函数,并将其添加到绘图中。然后,我可以得到所需的绘图外观,而不必从函数中返回绘图(这是否是个好主意是另一回事,但有可能)。
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
推荐答案
要构造一系列magrittr步骤,请从。
To construct a sequence of magrittr steps, start with .
action = . %>% group_by(am, gear) %>% summarise(mean = mean(mpg), sd = sd(mpg))
然后可以按照OP中的想象使用它:
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)
要查看所有步骤,请使用 functions(action )
或只需键入名称:
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.
这篇关于有没有一种方法可以“遍历列表”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!