逐步完成具有中间结果的管道 [英] Stepping through a pipeline with intermediate results
问题描述
是否有一种方法可以在不手动执行的情况下,在每个步骤中输出管道的结果? (例如,不选择并仅运行选定的块)
Is there a way to output the result of a pipeline at each step without doing it manually? (eg. without selecting and running only the selected chunks)
我经常发现自己逐行运行管道以记住其作用或时间我正在进行一些分析。
例如:
library(dplyr)
mtcars %>%
group_by(cyl) %>%
sample_frac(0.1) %>%
summarise(res = mean(mpg))
# Source: local data frame [3 x 2]
#
# cyl res
# 1 4 33.9
# 2 6 18.1
# 3 8 18.7
我要选择并运行:
mtcars %>% group_by(cyl)
然后...
mtcars %>% group_by(cyl) %>% sample_frac(0.1)
依此类推...
但是选择并在 RStudio
CMD / CTRL + ENTER
But selecting and CMD/CTRL
+ENTER
in RStudio
leaves a more efficient method to be desired.
这可以在协作中完成吗?德?
Can this be done in code?
是否存在接受管道并逐行运行/消化它的功能,以显示控制台中每一步的输出,然后按如下所示按Enter继续 demos(...)
或软件包指南的 examples(...)
Is there a function which takes a pipeline and runs/digests it line by line showing output at each step in the console and you continue by pressing enter like in demos(...)
or examples(...)
of package guides
推荐答案
使用magrittr函数链很容易。例如,使用以下函数定义函数 my_chain
:
It is easy with magrittr function chain. For example define a function my_chain
with:
foo <- function(x) x + 1
bar <- function(x) x + 1
baz <- function(x) x + 1
my_chain <- . %>% foo %>% bar %>% baz
并得到最终结果链为:
> my_chain(0)
[1] 3
您可以使用<$获得函数列表c $ c> functions(my_chain)
并定义一个 stepper函数,如下所示:
You can get a function list with functions(my_chain)
and define a "stepper" function like this:
stepper <- function(fun_chain, x, FUN = print) {
f_list <- functions(fun_chain)
for(i in seq_along(f_list)) {
x <- f_list[[i]](x)
FUN(x)
}
invisible(x)
}
并使用插入的 print
函数运行链:
And run the chain with interposed print
function:
stepper(my_chain, 0, print)
# [1] 1
# [1] 2
# [1] 3
或等待用户输入:
stepper(my_chain, 0, function(x) {print(x); readline()})
这篇关于逐步完成具有中间结果的管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!