debugging R中管道命令的反向打印/日志记录输出

w6lpcovy  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(137)

谁能解释一下这个R脚本的打印输出的逆序:

test_pipe = function(dta, txt) {
  print(txt)
  return(paste(dta,txt))
}

strg = '0'
strg = strg %>%
  test_pipe(1) %>%
  test_pipe(2) %>%
  test_pipe(3)
print(strg)

返回

[1] 3
[1] 2
[1] 1
[1] "0 1 2 3"

为什么3在1之前打印,而字符串输出按顺序携带数字?
如果我用www.example.com()替换这两个print()语句flog.info,那么所有输出都共享完全相同的时间戳:

INFO [2023-03-02 08:47:17] 3
INFO [2023-03-02 08:47:17] 2
INFO [2023-03-02 08:47:17] 1
INFO [2023-03-02 08:47:17] 0 1 2 3

这个例子模拟了试图调试一个长管道序列的真实的问题,使用print()语句来识别出错的函数。

des4xlb0

des4xlb01#

这是由于惰性求值。magrittr有一个eager管道可以避免这种情况(或者如果你控制test_pipe,插入force(dta)作为主体的第一行)。

library(magrittr)

strg = '0'
strg = strg %!>%
  test_pipe(1) %!>%
  test_pipe(2) %!>%
  test_pipe(3)
print(strg)
## [1] 1
## [1] 2
## [1] 3

相关问题