有没有办法在每一步输出管道的结果而不手动完成?(例如,不选择和仅运行选定的块)
我经常发现自己逐行运行管道以记住它正在做什么或何时开发一些分析.
例如:
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
Run Code Online (Sandbox Code Playgroud)
我要选择并运行:
mtcars %>% group_by(cyl)
Run Code Online (Sandbox Code Playgroud)
然后...
mtcars %>% group_by(cyl) %>% sample_frac(0.1)
Run Code Online (Sandbox Code Playgroud)
等等...
但选择和CMD/CTRL
+ ENTER
会RStudio
留下更有效的方法.
这可以在代码中完成吗?
是否有这需要一个管道和运行/通过显示在控制台中的每一步输出线消化它线功能,您继续通过按如同进入demos(...)
或examples(...)
包装指南
您可以使用三通运算符(%T>%
)和来选择要打印的结果print()
。T型操作员专门用于打印等副作用。
# i.e.
mtcars %>%
group_by(cyl) %T>% print() %>%
sample_frac(0.1) %T>% print() %>%
summarise(res = mean(mpg))
Run Code Online (Sandbox Code Playgroud)
使用 magrittr 函数链很容易。例如定义一个函数my_chain
:
foo <- function(x) x + 1
bar <- function(x) x + 1
baz <- function(x) x + 1
my_chain <- . %>% foo %>% bar %>% baz
Run Code Online (Sandbox Code Playgroud)
并得到链的最终结果为:
> my_chain(0)
[1] 3
Run Code Online (Sandbox Code Playgroud)
您可以获得一个函数列表functions(my_chain)
并定义一个“步进”函数,如下所示:
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)
}
Run Code Online (Sandbox Code Playgroud)
并使用插入函数运行链print
:
stepper(my_chain, 0, print)
# [1] 1
# [1] 2
# [1] 3
Run Code Online (Sandbox Code Playgroud)
或者等待用户输入:
stepper(my_chain, 0, function(x) {print(x); readline()})
Run Code Online (Sandbox Code Playgroud)