Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain arithmetic operators in dplyr with %>% pipe

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.

like image 230
agenis Avatar asked Dec 08 '14 18:12

agenis


People also ask

What is the %>% operator in R?

%>% 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).

What is a pipe in Dplyr?

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 .

How do you use the piping operator in R?

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.

Can you use pipes in a function in R?

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.


3 Answers

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
like image 184
jbaums Avatar answered Oct 16 '22 08:10

jbaums


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

like image 33
Henrik Avatar answered Oct 16 '22 07:10

Henrik


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)
like image 1
Phoenix Avatar answered Oct 16 '22 09:10

Phoenix