在 tidyverse 中不中断管道的情况下打印中间结果 [英] Printing intermediate results without breaking pipeline in tidyverse

查看:29
本文介绍了在 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

这篇关于在 tidyverse 中不中断管道的情况下打印中间结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆