在闭包中使用 magrittr 管道

use magrittr pipe within closures

1 让我们看这个例子:

1:3 %>% rep(.,2) + 1 %>% sum  #[1] 2 3 4 2 3 4

[2] R 正在做的是:

1:3 %>% rep(.,2) + (1 %>% sum)

[3] 我想让 R 做的是:(这会出错),我喜欢 18 那里。

1:3 %>% (rep(.,2) + 1) %>% sum  #Error in rep(., 2) : attempt to replicate an object of type 'closure'

[4] 所以我需要变得超级蹩脚:

tmp <- 1:3 %>% rep(.,2) + 1
tmp %>% sum #[1] 18

我怎样才能使 [3] 正常工作。有人可以向我解释错误信息吗?

编辑

来自here

Note that the variable x on the left side of %>% is applied as the first argument in the function on the right side. This default behaviour can be changed using . which is called a placeholder.

However, one important thing to remember is, when the . appears in nested expressions, the first-argument-rule is still applied. But this behaviour can be suppressed using the curly braces{ }

有趣的是,我不知道的是:

这等于:

1:3 %>% sum(rep(.,3))   #[1] 24
1:3 %>% sum(.,rep(.,3)) #[1] 24

这两个相等:

1:3 %>% {sum(rep(.,3))}  #[1] 18
1:3 %>% rep(.,3) %>% sum #[1] 18 

编辑2

> packageVersion("magrittr")
[1] ‘1.5’

这个:

?'%>%'

给出:(我不知道我的 %>% 运算符后面是什么包,老实说我不太喜欢那样)

Help on topic '%>%' was found in the following packages:

Pipe operator (in package tidyr in library C:/Program Files/R/R-3.3.2/library) magrittr forward-pipe operator (in package magrittr in library C:/Program Files/R/R-3.3.2/library) Pipe operator (in package stringr in library C:/Program Files/R/R-3.3.2/library) Objects exported from other packages (in package dplyr in library C:/Program Files/R/R-3.3.2/library)

二元运算符 + 造成了问题。它的优先级低于管道(参见 ?Syntax)。在管道求和之前将整个操作括在括号中,或者使用 +:

的函数形式
(1:3 %>% rep(.,2) + 1) %>% sum
[1] 18

1:3 %>% rep(.,2) %>% `+`(1) %>% sum
[1] 18