Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe operator %>% error with seq() function in R

Tags:

r

pipe

dplyr

I'm a big fan of the %>% operator from magrittr/dplyr and use it whenever possible. I'm having problems, however, using it to pipe to the seq() function.

As a trivial example, imagine I have a variable x, and I want to create a sequence from x-5 to x+5. I could do it like this:

> x <- 10
> seq(from = x-5, to = x+5, by = 1)
 [1]  5  6  7  8  9 10 11 12 13 14 15

But for the life of me I can't get it to work properly with piping. To demonstrate, let me sneak up on the problem a little bit. Assume x <- 10.

Piping works in some situations ...

The following example silently pipes 10 to the from parameter and uses the ., along with some arithmetic, to set the to parameter to 15, giving a sequence 10:15 as expected.

> x %>% seq(.+5)
[1] 10 11 12 13 14 15

I can explicitly set the from parameter as below, and it also gives the same, expected result (10:15):

> x %>% seq(from = ., to = .+5)
[1] 10 11 12 13 14 15

But doesn't work in others ...

Now a little tweak on the previous example. I want to try to replicate my initial example and produce a sequence from x-5 to x+5. I would expect that I could set the from parameter to .-5, but this does not give the expected result:

> x %>% seq(from = .-5, to = .+5)
[1]  5 15

It seems that the from and to are being correctly set to 5 and 15 respectively. But it appears that the by parameter has been set to . (i.e. 10) to give the unexpected result 5 15 rather than the sequence 5:15.

I can try to explicitly set the by parameter, but now I get an error:

> x %>% seq(from = .-5, to = .+5, by = 1)
Error in seq.default(., from = . - 5, to = . + 5, by = 1) : 
  too many arguments

You can see what it has done here, piping the . to the first parameter, but then it has my three explicit parameters to deal with also, and the error results.

It worked fine right up until I wanted to do some arithmetic using . in the from parameter.

Is there a way to do what I want to do, or is it just a fact of life that certain functions are not fully compatible with %>%?

like image 879
Stuart Allen Avatar asked Dec 11 '17 23:12

Stuart Allen


1 Answers

You can prevent %>% from inserting . into the first argument by surrounding the right hand side with brace brackets:

10 %>% { seq(from = .-5, to = .+5) }
## [1]  5  6  7  8  9 10 11 12 13 14 15
like image 131
G. Grothendieck Avatar answered Oct 27 '22 12:10

G. Grothendieck