当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R magrittr pipe-eager 热切的管子


%>% 是惰性的,仅在需要时评估管道表达式,而 %!>% 是即刻的,并在每一步评估管道输入。当函数因副作用而被调用时(例如显示消息),这会产生更直观的行为。

请注意,您也可以通过使函数严格化来解决此问题。对函数中的第一个参数调用 force() 以强制顺序求值,即使使用惰性 %>% 管道也是如此。请参阅示例部分。

用法

lhs %!>% rhs

参数

lhs

值或 magrittr 占位符。

rhs

使用 magrittr 语义的函数调用。

例子

f <- function(x) {
  message("foo")
  x
}
g <- function(x) {
  message("bar")
  x
}
h <- function(x) {
  message("baz")
  invisible(x)
}

# The following lazy pipe sequence is equivalent to `h(g(f()))`.
# Given R's lazy evaluation behaviour,`f()` and `g()` are lazily
# evaluated when `h()` is already running. This causes the messages
# to appear in reverse order:
NULL %>% f() %>% g() %>% h()
#> baz
#> bar
#> foo

# Use the eager pipe to fix this:
NULL %!>% f() %!>% g() %!>% h()
#> foo
#> bar
#> baz

# Or fix this by calling `force()` on the function arguments
f <- function(x) {
  force(x)
  message("foo")
  x
}
g <- function(x) {
  force(x)
  message("bar")
  x
}
h <- function(x) {
  force(x)
  message("baz")
  invisible(x)
}

# With strict functions, the arguments are evaluated sequentially
NULL %>% f() %>% g() %>% h()
#> foo
#> bar
#> baz

# Instead of forcing, you can also check the type of your functions.
# Type-checking also has the effect of making your function lazy.

源代码:R/pipe.R

相关用法


注:本文由纯净天空筛选整理自Stefan Milton Bache等大神的英文原创作品 Eager pipe。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。