【问题标题】:dplyr and mid-pipe messagesdplyr 和中间管道消息
【发布时间】:2021-07-11 11:46:18
【问题描述】:

我偶尔会有长时间运行的管道,随着阶段的进展,我想要一个快速的message。我在努力

log_midpipe <- function(x, expr) { expr; x; }

(也试过force(expr)),但是消息时机全错了。

library(dplyr)
sleep <- function(x, time=3) { Sys.sleep(3); x; }
message(Sys.time(), " start"); 
mtcars %>%
  log_midpipe(message(Sys.time(), " hello1")) %>%
  sleep(.) %>%
  log_midpipe(message(Sys.time(), " hello2")) %>%
  sleep(.) %>%
  head(3)
message(Sys.time(), " done")
# 2021-04-16 08:51:09 start
# 2021-04-16 08:51:12 hello2
# 2021-04-16 08:51:15 hello1
# 2021-04-16 08:51:15 done
#                mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

乱序是(我相信)因为参数的评估方式:懒惰,一旦从管道转换为嵌套的“类似括号”的命令堆栈,"hello1" 消息传递是外部的-most,这意味着它被评估last

是否有一种简单的方法可以实时获取中间管道日志记录?

我希望得到

# 2021-04-16 08:51:09 start
# 2021-04-16 08:51:09 hello1
# 2021-04-16 08:51:12 hello2
# 2021-04-16 08:51:15 done

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    您可以通过强制 log_midpipe 首先评估 x 来将它们排列成正确的顺序。

    这应该适用于实际示例,其中长时间运行的代码是 sleep 中的 x 的一部分,而不是事先单独调用,因为 Sys.sleep 不需要评估 x 的任何部分。

    log_midpipe <- function(x, expr) {
      result <- x
      expr 
      result
    }
    

    需要x 作为输入来执行其长期运行过程的sleep 看起来像这样并以正确的间隔打印:

    sleep <- function(x, time=3) { 
      result <- x
      Sys.sleep(3)
      result
    }
    

    【讨论】:

    • 我在log_midpipe 中非常关注force(x),以至于我没想过要强制表达,很好。 并且 ...您发现了我设计的(未在生产中使用)sleep 函数的问题,这表明中间管道步骤也可能加剧该问题,而不仅仅是中间管道日志。谢谢!
    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多