在 tidyverse 中不中断管道的情况下打印中间结果

问题描述:

是否有一个命令可以添加到 tidyverse 管道中,它不会中断流程,但会产生一些副作用,比如打印出一些东西.我想到的用例是这样的.如果是管道

Is there a command to add to tidyverse pipelines that does not break the flow, but produces some side effect, like printing something out. The usecase I have in mind is something like this. In case of a pipeline

data %>%
  mutate(new_var = <some time consuming operation>) %>%
  mutate(new_var2 = <some other time consuming operation>) %>%
  ...

我想向管道添加一些不会修改最终结果的命令,但会打印出一些进度或事情的状态.也许是这样的:

I would like to add some command to the pipeline that would not modify the end result, but would print out some progress or the state of things. Maybe something like this:

data %>%
  mutate(new_var = <some time consuming operation>) %>%
  command_x(print("first operation done")) %>%
  mutate(new_var2 = <some other time consuming operation>) %>%
  ...

是否已经存在这样的command_x?

您可以轻松编写自己的函数

You could easily write your own function

pass_through <- function(data, fun) {fun(data); data}

然后像这样使用

mtcars %>% pass_through(. %>% ncol %>% print) %>% nrow

这里我们使用.%>% 语法来创建匿名函数.您也可以使用

Here we use the . %>% syntax to create an anonymous function. You could also write your own more explicitly with

mtcars %>% pass_through(function(x) print(ncol(x))) %>% nrow