I would like to understand why, in the the dplyr
or magrittr
package, and more specifically the chaining function %>%
has some trouble with the basic operators +
, -
, *
, and /
Chaining takes the output of previous statement and feeds it as first argument of the next:
1:10 %>% sum
# [55]
Thus how come this doesn't work
1:10 %>% *2 %>% sum
1:10 %>% .*2 %>% sum
I also found that the following syntax works for adding/substracting, but not multiply or divide. why so?
1:10 %>% +(2) # works OK
1:10 %>% *(2) # nope...
So should I write an anonymous function even to do a *2
operation on my data.frame?
1:10 %>% (function(x) x*2) %>% sum
Thanks, I couldn't find the answer in other SO questions.
%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).
Pipes let you take the output of one function and send it directly to the next, which is useful when you need to many things to the same data set. Pipes in R look like %>% and are made available via the magrittr package installed as part of dplyr .
The pipe operator is a special operational function available under the magrittr and dplyr package (basically developed under magrittr), which allows us to pass the result of one function/argument to the other one in sequence. It is generally denoted by symbol %>% in R Programming.
The pipe operator, written as %>% , has been a longstanding feature of the magrittr package for R. It takes the output of one function and passes it into another function as an argument. This allows us to link a sequence of analysis steps.
Surround the operators with backticks or quotes, and things should work as expected:
1:10 %>% `*`(2) %>% sum
# [1] 110
1:10 %>% `/`(2) %>% sum
# [1] 27.5
Or use the Aliases
in magrittr
package, e.g.:
1:10 %>% multiply_by(2)
# [1] 2 4 6 8 10 12 14 16 18 20
1:10 %>% add(2)
# [1] 3 4 5 6 7 8 9 10 11 12
The Aliases
include 'words' for boolean operators, extract/replace, and arithmetic operators
As an addition to the answer above, it is handy to use Aliases
in magrittr
package, e.g.:
magrittr's pipeable operator replacements
operator | functional alternative |
---|---|
x * y | x %>% multiply_by(y) |
x ^ y | x %>% raise_to_power(y) |
x[y] | x %>% extract(y) |
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