%>%
是惰性的,僅在需要時評估管道表達式,而 %!>%
是即刻的,並在每一步評估管道輸入。當函數因副作用而被調用時(例如顯示消息),這會產生更直觀的行為。
請注意,您也可以通過使函數嚴格化來解決此問題。對函數中的第一個參數調用 force()
以強製順序求值,即使使用惰性 %>%
管道也是如此。請參閱示例部分。
例子
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 magrittr pipe 管道
- R magrittr exposition 展覽管
- R magrittr tee 三通管
- R magrittr compound 分配管道
- R matrix轉list用法及代碼示例
- R SparkR match用法及代碼示例
- R vcov.gam 從 GAM 擬合中提取參數(估計器)協方差矩陣
- R gam.check 擬合 gam 模型的一些診斷
- R as 強製對象屬於某個類
- R null.space.dimension TPRS 未懲罰函數空間的基礎
- R language-class 表示未評估語言對象的類
- R gam.reparam 尋找平方根懲罰的穩定正交重新參數化。
- R className 類名包含對應的包
- R modelr typical 求典型值
- R extract.lme.cov 從 lme 對象中提取數據協方差矩陣
- R scat 用於重尾數據的 GAM 縮放 t 係列
- R choldrop 刪除並排名第一 Cholesky 因子更新
- R smooth.construct.cr.smooth.spec GAM 中的懲罰三次回歸樣條
- R modelr resample “惰性”重采樣。
- R bandchol 帶對角矩陣的 Choleski 分解
- R BasicClasses 基本數據類型對應的類
- R gam.side GAM 的可識別性邊條件
- R cox.ph 附加 Cox 比例風險模型
- R callGeneric 從方法調用當前通用函數
- R mgcv.parallel mgcv 中的並行計算。
注:本文由純淨天空篩選整理自Stefan Milton Bache等大神的英文原創作品 Eager pipe。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。