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
.
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
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 %>%
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With