當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。