Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use magrittr pipe within closures

1 Lets look at this example:

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

[2] What R is doing is:

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

[3] What I want R to do is: (which gives an error) , I like to get 18 there.

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

[4] So I need to go super lame:

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

How can I fix [3] to work. Can someone explain me the error message?

Edit

From 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{ }

Interestingly, what I didn't know:

This is the equal:

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

And these two are equal:

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

Edit2

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

This:

?'%>%'

gives: (I don't know what package is behind my %>% operator, I don't like that too much to be honest)

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)

like image 781
Andre Elrico Avatar asked Oct 16 '22 22:10

Andre Elrico


1 Answers

The binary operator + is creating the problem. It has lower precedence than the pipe (see ?Syntax). Either enclose the entire operation in parentheses before piping to sum, or use the functional form of +:

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

1:3 %>% rep(.,2) %>% `+`(1) %>% sum
[1] 18
like image 135
James Avatar answered Oct 21 '22 06:10

James