x %>% f() 和 x %T>% f() 都运行 f(x),但区别在于第一个返回 f(x) 的输出,而第二个返回 x。
1) 情节。 %T>% 通常与 plot 或其他不返回任何内容的命令一起使用。运行此类命令是因为它们的副作用,在这种情况下是绘图,而不是它们的返回值。因为plot 只返回NULL,所以BOD %>% plot 也只返回NULL,所以如果我们想继续在管道中进行,我们不能。如果我们使用%T>% 而不是%>%,那么我们仍然可以。
library(dplyr)
library(magrittr)
BOD %T>%
plot %>%
mutate(demand = demand + 1)
2) 字符串。另一个例子是,如果我们想通过查看中间结果来调试管道。 str 不返回任何内容,所以如果我们想继续管道,我们可以使用 %T>% 。
library(dplyr)
library(magrittr)
BOD %T>%
str %>%
mutate(demand = demand + 1)
3) lm/summary 假设我们想在管道中显示来自summary 的输出,然后继续计算残差平方和,即deviance。我们希望将deviance 应用于lm 的输出,而不是print(summary(.)) 的输出。注意:当管道进入括号表达式时,必须显式使用 .,如 summary(.) 所示。
library(dplyr)
library(magrittr)
BOD %>%
lm(demand ~ Time, data = .) %T>%
{ summary(.) %>% print } %>%
deviance
4) lm 假设我们想分别在 1:4、2:5 和 3:6 行上运行 lm。然后我们可以像这样多次使用%T>%:
library(magrittr)
BOD %T>%
{ lm(demand ~ Time, data = ., subset = 1:4) %>% print } %T>%
{ lm(demand ~ Time, data = ., subset = 2:5) %>% print } %>%
{ lm(demand ~ Time, data = ., subset = 3:6) %>% print }
这个例子确实说明了%T>% 在同一管道中的多种用途;但是,使用update 可以更轻松地完成此操作,而无需使用任何管道。
fm <- lm(demand ~ Time, data = BOD)
update(fm, subset = 1:4)
update(fm, subset = 2:5)
update(fm, subset = 3:6)
替代品
在没有%T>% 的情况下可以通过其他方式获得相同的效果。使用第一个示例,这将运行 plot 显式返回输入点。
library(dplyr)
BOD %>%
{ plot(.); . } %>%
mutate(demand = demand + 1)
第二种选择是将其分成两个管道:
library(dplyr)
BOD %>% plot
BOD %>% mutate(demand = demand + 1)
第三种选择是定义一个返回其输入的函数:
library(dplyr)
plot_ <- function(data, ...) { plot(data, ...); data }
BOD %>%
plot_ %>%
mutate(demand = demand + 1)
类似的替代方案也适用于其他示例。