R中的%T>%函数是什么意思?

时间:2020-01-01 09:59:55

标签: r

能否请您解释一下此管道-%T>%,并提供一些示例。我发现该情节只有一个例子:

rnorm(200) %>%
matrix(ncol = 2) %T>%
plot %>% # plot usually does not return anything.
colSums

https://www.rdocumentation.org/packages/magrittr/versions/1.5/topics/%25T%3E%25

但是从这个和描述中我不理解用法。 谢谢

2 个答案:

答案 0 :(得分:4)

library(magrittr)

管道运算符%>%返回RHS值

c(1, 2) %>% sum
#[1] 3

c(1, 2) %>% sum %>% sqrt
#[1] 1.73205

%T>%返回原始LHS值

c(1, 2) %T>% sum
#[1] 1 2

c(1, 2) %T>% sum %T>% sqrt
#[1] 1 2

答案 1 :(得分:4)

x %>% f()x %T>% f()都运行f(x),但是不同之处在于,第一个返回f(x)的输出,而第二个返回x。 / p>

1)情节%T>%通常与plot或其他不返回任何内容的命令一起使用。运行此类命令是出于其副作用(在本例中为绘图),而不是其返回值。由于plot仅返回NULL,因此BOD %>% plot也仅返回NULL,因此如果我们要继续进行下去,就不能这样做。如果我们使用%>%代替%T>%,那么我们仍然可以。

library(dplyr)
library(magrittr)

BOD %T>%
  plot %>%
  mutate(demand = demand + 1)

2)str 。另一个示例是,如果我们想通过查看中间结果来调试管道。 str不返回任何内容,因此,如果我们想继续在管道中使用,可以使用%T>%

library(dplyr)
library(magrittr)

BOD %T>%
  str %>%
  mutate(demand = demand + 1)

3)lm / summary 假设我们要在管道中显示Summary的输出,然后继续计算残差平方和,即deviance。我们希望将deviance应用于lm的输出,而不是print(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)

类似的替代方法也可以应用于其他示例。